<template>
  <div>
    <div class="page-header">
      <h2>Subnets</h2>
      <button class="btn btn-primary" @click="openModal()">+ Add Subnet</button>
    </div>

    <!-- Filters -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search subnets..."
        @input="debouncedSearch"
      />
      <select v-model="vlanFilter" class="form-control" @change="applyFilter">
        <option value="">All VLANs</option>
        <option v-for="vlan in vlans" :key="vlan.vlanid" :value="vlan.vlanid">
          VLAN {{ vlan.vlannumber }} - {{ vlan.name }}
        </option>
      </select>
      <select v-model="typeFilter" class="form-control" @change="applyFilter">
        <option value="">All Types</option>
        <option value="ipv4">IPv4</option>
        <option value="ipv6">IPv6</option>
      </select>
    </div>

    <div class="card">
      <div v-if="loading" class="loading">Loading...</div>

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>CIDR</th>
                <th>Name</th>
                <th>VLAN</th>
                <th>Gateway</th>
                <th>DHCP</th>
                <th>Location</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="subnet in subnets" :key="subnet.subnetid">
                <td class="mono">{{ subnet.cidr }}</td>
                <td>{{ subnet.name }}</td>
                <td>
                  <span v-if="subnet.vlanname">
                    VLAN {{ subnet.vlannumber }} - {{ subnet.vlanname }}
                  </span>
                  <span v-else>-</span>
                </td>
                <td class="mono">{{ subnet.gatewayip || '-' }}</td>
                <td>
                  <span class="badge" :class="subnet.dhcpenabled ? 'badge-success' : 'badge-secondary'">
                    {{ subnet.dhcpenabled ? 'Enabled' : 'Disabled' }}
                  </span>
                </td>
                <td>{{ subnet.locationname || '-' }}</td>
                <td class="actions">
                  <button
                    class="btn btn-secondary btn-sm"
                    @click="openModal(subnet)"
                  >
                    Edit
                  </button>
                  <button
                    class="btn btn-danger btn-sm"
                    @click="confirmDelete(subnet)"
                  >
                    Delete
                  </button>
                </td>
              </tr>
              <tr v-if="subnets.length === 0">
                <td colspan="7" style="text-align: center; color: var(--text-light);">
                  No subnets found
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <PaginationBar
          :page="page"
          :totalPages="totalPages"
          :perPage="perPage"
          @update:page="goToPage"
          @update:perPage="changePerPage"
        />
      </template>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showModal" class="modal-overlay">
      <div class="modal modal-lg">
        <div class="modal-header">
          <h3>{{ editingSubnet ? 'Edit Subnet' : 'Add Subnet' }}</h3>
        </div>
        <form @submit.prevent="saveSubnet">
          <div class="modal-body">
            <!-- Basic Info -->
            <div class="form-section">
              <h4>Basic Information</h4>
              <div class="form-row">
                <div class="form-group">
                  <label for="cidr">CIDR *</label>
                  <input
                    id="cidr"
                    v-model="form.cidr"
                    type="text"
                    class="form-control"
                    placeholder="e.g., 10.1.1.0/24"
                    required
                  />
                </div>

                <div class="form-group">
                  <label for="name">Name *</label>
                  <input
                    id="name"
                    v-model="form.name"
                    type="text"
                    class="form-control"
                    required
                  />
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label for="vlanid">VLAN</label>
                  <select id="vlanid" v-model="form.vlanid" class="form-control">
                    <option value="">Select VLAN</option>
                    <option v-for="vlan in vlans" :key="vlan.vlanid" :value="vlan.vlanid">
                      VLAN {{ vlan.vlannumber }} - {{ vlan.name }}
                    </option>
                  </select>
                </div>

                <div class="form-group">
                  <label for="locationid">Location</label>
                  <select id="locationid" v-model="form.locationid" class="form-control">
                    <option value="">Select Location</option>
                    <option v-for="loc in locations" :key="loc.locationid" :value="loc.locationid">
                      {{ loc.locationname }}
                    </option>
                  </select>
                </div>
              </div>

              <div class="form-group">
                <label for="description">Description</label>
                <textarea
                  id="description"
                  v-model="form.description"
                  class="form-control"
                  rows="2"
                ></textarea>
              </div>
            </div>

            <!-- Network Details -->
            <div class="form-section">
              <h4>Network Details</h4>
              <div class="form-row">
                <div class="form-group">
                  <label for="gatewayip">Gateway IP</label>
                  <input
                    id="gatewayip"
                    v-model="form.gatewayip"
                    type="text"
                    class="form-control"
                    placeholder="e.g., 10.1.1.1"
                  />
                </div>

                <div class="form-group">
                  <label for="subnetmask">Subnet Mask</label>
                  <input
                    id="subnetmask"
                    v-model="form.subnetmask"
                    type="text"
                    class="form-control"
                    placeholder="e.g., 255.255.255.0"
                  />
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label for="dns1">Primary DNS</label>
                  <input
                    id="dns1"
                    v-model="form.dns1"
                    type="text"
                    class="form-control"
                  />
                </div>

                <div class="form-group">
                  <label for="dns2">Secondary DNS</label>
                  <input
                    id="dns2"
                    v-model="form.dns2"
                    type="text"
                    class="form-control"
                  />
                </div>
              </div>
            </div>

            <!-- DHCP Settings -->
            <div class="form-section">
              <h4>DHCP Settings</h4>
              <div class="form-group checkbox-group">
                <label>
                  <input type="checkbox" v-model="form.dhcpenabled" />
                  <span>DHCP Enabled</span>
                </label>
              </div>

              <div v-if="form.dhcpenabled" class="form-row">
                <div class="form-group">
                  <label for="dhcprangestart">DHCP Range Start</label>
                  <input
                    id="dhcprangestart"
                    v-model="form.dhcprangestart"
                    type="text"
                    class="form-control"
                    placeholder="e.g., 10.1.1.100"
                  />
                </div>

                <div class="form-group">
                  <label for="dhcprangeend">DHCP Range End</label>
                  <input
                    id="dhcprangeend"
                    v-model="form.dhcprangeend"
                    type="text"
                    class="form-control"
                    placeholder="e.g., 10.1.1.200"
                  />
                </div>
              </div>
            </div>

            <div v-if="error" class="error-message">{{ error }}</div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="closeModal">Cancel</button>
            <button type="submit" class="btn btn-primary" :disabled="saving">
              {{ saving ? 'Saving...' : 'Save' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
      <div class="modal">
        <div class="modal-header">
          <h3>Delete Subnet</h3>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete subnet <strong>{{ subnetToDelete?.cidr }}</strong>?</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteSubnet">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { networkApi, locationsApi } from '@/api'
import PaginationBar from '@/components/PaginationBar.vue'
import { useToast } from '@/composables/toast'
import { apiError } from '@/utils/apiError'
import { useListQuery } from '@/composables/listQuery'
const toast = useToast()

const route = useRoute()

const subnets = ref([])
const vlans = ref([])
const locations = ref([])
const loading = ref(true)
const { page, search, setPage, setSearch } = useListQuery({ onChange: loadSubnets })
const vlanFilter = ref('')
const typeFilter = ref('')
const totalPages = ref(1)
const perPage = ref(20)

const showModal = ref(false)
const editingSubnet = ref(null)
const saving = ref(false)
const error = ref('')

const showDeleteModal = ref(false)
const subnetToDelete = ref(null)

const form = ref({
  cidr: '',
  name: '',
  description: '',
  gatewayip: '',
  subnetmask: '',
  vlanid: '',
  locationid: '',
  subnettype: '',
  dhcpenabled: true,
  dhcprangestart: '',
  dhcprangeend: '',
  dns1: '',
  dns2: ''
})

let searchTimeout = null

onMounted(async () => {
  // Check for vlanid query parameter
  if (route.query.vlanid) {
    vlanFilter.value = route.query.vlanid
  }

  await Promise.all([
    loadVLANs(),
    loadLocations()
  ])
  await loadSubnets()
})

async function loadVLANs() {
  try {
    const response = await networkApi.vlans.list({ perpage: 100 })
    vlans.value = response.data.data || []
  } catch (err) {
    console.error('Error loading VLANs:', err)
  }
}

async function loadLocations() {
  try {
    const response = await locationsApi.list({ perpage: 100 })
    locations.value = response.data.data || []
  } catch (err) {
    console.error('Error loading locations:', err)
  }
}

// A filter change must go back to page 1. Selecting a filter while on page 5
// asked the server for page 5 of a result set that now has one page, and the
// list came back empty as though the filter matched nothing.
//
// setPage(1) writes the URL, which the composable's watcher picks up and
// answers with onChange - so calling the loader as well would fetch twice.
// Load directly only when already on page 1, where nothing changes and the
// watcher stays silent.
function applyFilter() {
  if (page.value > 1) setPage(1)
  else loadSubnets()
}

async function loadSubnets() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: perPage.value
    }
    if (search.value) params.search = search.value
    if (vlanFilter.value) params.vlanid = vlanFilter.value
    if (typeFilter.value) params.type = typeFilter.value

    const response = await networkApi.subnets.list(params)
    subnets.value = response.data.data || []
    totalPages.value = response.data.meta?.pagination?.totalpages || response.data.meta?.pagination?.total_pages || 1
  } catch (err) {
    console.error('Error loading subnets:', err)
  } finally {
    loading.value = false
  }
}

function debouncedSearch() {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    setSearch(search.value)
    loadSubnets()
  }, 300)
}

function goToPage(p) {
  setPage(p)
  loadSubnets()
}

function changePerPage(newPerPage) {
  perPage.value = newPerPage
  setPage(1)
  loadSubnets()
}

function openModal(subnet = null) {
  editingSubnet.value = subnet
  if (subnet) {
    form.value = {
      cidr: subnet.cidr || '',
      name: subnet.name || '',
      description: subnet.description || '',
      gatewayip: subnet.gatewayip || '',
      subnetmask: subnet.subnetmask || '',
      vlanid: subnet.vlanid || '',
      locationid: subnet.locationid || '',
      subnettype: subnet.subnettype || '',
      dhcpenabled: subnet.dhcpenabled ?? true,
      dhcprangestart: subnet.dhcprangestart || '',
      dhcprangeend: subnet.dhcprangeend || '',
      dns1: subnet.dns1 || '',
      dns2: subnet.dns2 || ''
    }
  } else {
    form.value = {
      cidr: '',
      name: '',
      description: '',
      gatewayip: '',
      subnetmask: '',
      vlanid: vlanFilter.value || '',
      locationid: '',
      subnettype: '',
      dhcpenabled: true,
      dhcprangestart: '',
      dhcprangeend: '',
      dns1: '',
      dns2: ''
    }
  }
  error.value = ''
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  editingSubnet.value = null
}

async function saveSubnet() {
  error.value = ''
  saving.value = true

  try {
    const payload = {
      cidr: form.value.cidr,
      name: form.value.name,
      description: form.value.description || null,
      gatewayip: form.value.gatewayip || null,
      subnetmask: form.value.subnetmask || null,
      vlanid: form.value.vlanid || null,
      locationid: form.value.locationid || null,
      subnettype: form.value.subnettype || null,
      dhcpenabled: form.value.dhcpenabled,
      dhcprangestart: form.value.dhcprangestart || null,
      dhcprangeend: form.value.dhcprangeend || null,
      dns1: form.value.dns1 || null,
      dns2: form.value.dns2 || null
    }

    if (editingSubnet.value) {
      await networkApi.subnets.update(editingSubnet.value.subnetid, payload)
    } else {
      await networkApi.subnets.create(payload)
    }
    closeModal()
    loadSubnets()
  } catch (err) {
    console.error('Error saving subnet:', err)
    error.value = apiError(err, 'Failed to save subnet')
  } finally {
    saving.value = false
  }
}

function confirmDelete(subnet) {
  subnetToDelete.value = subnet
  showDeleteModal.value = true
}

async function deleteSubnet() {
  try {
    await networkApi.subnets.delete(subnetToDelete.value.subnetid)
    showDeleteModal.value = false
    subnetToDelete.value = null
    loadSubnets()
  } catch (err) {
    console.error('Error deleting subnet:', err)
    toast.error(apiError(err, 'Failed to delete subnet'))
  }
}
</script>

<style scoped>
.mono {
  font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
}

.filters {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.filters input {
  flex: 1;
  min-width: 200px;
}

.filters select {
  width: auto;
  min-width: 150px;
}

.modal-lg {
  max-width: 700px;
}

.form-section {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--border);
}

.form-section:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

.form-section h4 {
  margin: 0 0 1rem 0;
  font-size: 0.95rem;
  color: var(--text-light);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
  width: 1.125rem;
  height: 1.125rem;
}

.badge-secondary {
  background: var(--secondary);
  color: var(--text);
}
</style>
