<template>
  <div>
    <div class="page-header">
      <h2>Network Devices</h2>
      <router-link to="/print/asset-label-batch/network_device" class="btn btn-secondary" target="_blank">Print Labels</router-link>
      <router-link to="/network/new" class="btn btn-primary">Add Device</router-link>
    </div>

    <!-- Type Tabs -->
    <div class="type-tabs">
      <button
        :class="{ active: selectedType === null }"
        @click="selectType(null)"
      >
        All ({{ totalCount }})
      </button>
      <button
        v-for="t in deviceTypes"
        :key="t.networkdevicetypeid"
        :class="{ active: selectedType === t.networkdevicetypeid }"
        @click="selectType(t.networkdevicetypeid)"
      >
        {{ t.networkdevicetype }} ({{ t.count || 0 }})
      </button>
    </div>

    <!-- Filters -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search by hostname, asset #, serial..."
        @input="debouncedSearch"
      />
      <select v-model="vendorFilter" class="form-control" @change="applyFilter">
        <option value="">All Vendors</option>
        <option v-for="v in vendors" :key="v.vendorid" :value="v.vendorid">
          {{ v.vendor }}
        </option>
      </select>
      <select v-model="locationFilter" class="form-control" @change="applyFilter">
        <option value="">All Locations</option>
        <option v-for="loc in locations" :key="loc.locationid" :value="loc.locationid">
          {{ loc.locationname }}
        </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>Asset Tag</th>
                <th>Hostname</th>
                <th>Serial Number</th>
                <th>Device Type</th>
                <th>Vendor</th>
                <th>Features</th>
                <th>Status</th>
                <th>Location</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="device in devices" :key="device.networkdevice?.networkdeviceid || device.assetid" class="clickable-row" @click="$router.push(`/network/${device.networkdevice?.networkdeviceid || device.assetid}`)">
                <td>{{ device.assetnumber }}</td>
                <td class="mono">{{ device.networkdevice?.hostname || '-' }}</td>
                <td class="mono">{{ device.serialnumber || '-' }}</td>
                <td>{{ device.networkdevice?.networkdevicetypename || '-' }}</td>
                <td>{{ device.networkdevice?.vendorname || '-' }}</td>
                <td class="features">
                  <span v-if="device.networkdevice?.ispoe" class="feature-tag poe">PoE</span>
                  <span v-if="device.networkdevice?.ismanaged" class="feature-tag managed">Managed</span>
                  <span v-if="device.networkdevice?.portcount" class="feature-tag ports">{{ device.networkdevice.portcount }} ports</span>
                  <span v-if="!device.networkdevice?.ispoe && !device.networkdevice?.ismanaged && !device.networkdevice?.portcount">-</span>
                </td>
                <td>
                  <span class="badge" :style="colorStyle(device.statuscolor)">
                    {{ device.statusname || 'Unknown' }}
                  </span>
                </td>
                <td>{{ device.locationname || '-' }}</td>
                <td class="actions" @click.stop>
                  <router-link
                    :to="`/network/${device.networkdevice?.networkdeviceid}`"
                    class="btn btn-secondary btn-sm"
                  >
                    View
                  </router-link>
                </td>
              </tr>
              <tr v-if="devices.length === 0">
                <td colspan="9" style="text-align: center; color: var(--text-light);">
                  No network devices found
                  <SearchSuggestion :suggestion="suggestion" @pick="applySuggestion" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

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

<script setup>
import { ref, onMounted } from 'vue'
import { colorStyle } from "@/utils/colorStyle"
import { networkApi, vendorsApi, locationsApi } from '@/api'
import PaginationBar from '@/components/PaginationBar.vue'
import { useListQuery } from '@/composables/listQuery'
import SearchSuggestion from '@/components/SearchSuggestion.vue'

const devices = ref([])
const deviceTypes = ref([])
const vendors = ref([])
const locations = ref([])
const loading = ref(true)
const { page, search, setPage, setSearch, suggestion, reportCount } = useListQuery({ onChange: loadDevices })

// Take the offered spelling. setSearch only syncs the URL and the watcher
// that reloads is suppressed because search.value already holds the new
// term, so load directly.
function applySuggestion(word) {
  search.value = word
  setSearch(word)
  loadDevices()
}
const selectedType = ref(null)
const vendorFilter = ref('')
const locationFilter = ref('')
const totalPages = ref(1)
const perPage = ref(25)
const totalCount = ref(0)

let searchTimeout = null

onMounted(async () => {
  await Promise.all([
    loadDeviceTypes(),
    loadVendors(),
    loadLocations()
  ])
  await loadDevices()
})

async function loadDeviceTypes() {
  try {
    const response = await networkApi.types.list({ perpage: 100 })
    deviceTypes.value = response.data.data || []
    // Get counts for each type
    await updateTypeCounts()
  } catch (error) {
    console.error('Error loading device types:', error)
  }
}

async function updateTypeCounts() {
  // Get summary for type counts
  try {
    const response = await networkApi.dashboardSummary()
    const byType = response.data.data?.bytype || response.data.data?.by_type || []
    totalCount.value = response.data.data?.total || 0

    // Map counts to types
    deviceTypes.value = deviceTypes.value.map(t => {
      const found = byType.find(bt => bt.type === t.networkdevicetype)
      return { ...t, count: found?.count || 0 }
    })
  } catch (error) {
    console.error('Error loading type counts:', error)
  }
}

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

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

// 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 loadDevices()
}

async function loadDevices() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: perPage.value
    }
    if (search.value) params.search = search.value
    if (selectedType.value) params.typeid = selectedType.value
    if (vendorFilter.value) params.vendorid = vendorFilter.value
    if (locationFilter.value) params.locationid = locationFilter.value

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

function selectType(typeId) {
  selectedType.value = typeId
  setPage(1)
  loadDevices()
}

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

function goToPage(p) {
  if (p >= 1 && p <= totalPages.value) {
    setPage(p)
    loadDevices()
  }
}

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

function getStatusClass(status) {
  if (!status) return 'badge-info'
  const s = status.toLowerCase()
  if (s === 'in use' || s === 'active') return 'badge-success'
  if (s === 'in repair' || s === 'maintenance') return 'badge-warning'
  if (s === 'retired' || s === 'decommissioned') return 'badge-danger'
  return 'badge-info'
}
</script>

<style scoped>
.type-tabs {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.type-tabs button {
  padding: 0.5rem 1rem;
  border: 1px solid var(--border);
  background: var(--bg-card);
  color: var(--text);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.type-tabs button:hover {
  background: var(--bg);
  border-color: var(--primary);
}

.type-tabs button.active {
  background: var(--primary);
  color: white;
  border-color: var(--primary);
}

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

.filters .form-control {
  flex: 1;
  min-width: 150px;
}

.filters select.form-control {
  flex: 0 0 auto;
  width: auto;
  min-width: 150px;
}

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

.features {
  display: flex;
  gap: 0.375rem;
  flex-wrap: wrap;
}

.feature-tag {
  display: inline-block;
  padding: 0.2rem 0.5rem;
  font-size: 0.75rem;
  border-radius: 4px;
  background: var(--bg);
  color: var(--text-light);
}

.feature-tag.poe {
  background: #d4edda;
  color: #155724;
}

.feature-tag.managed {
  background: #e3f2fd;
  color: #1565c0;
}

.feature-tag.ports {
  background: var(--bg);
  color: var(--text-light);
}

@media (prefers-color-scheme: dark) {
  .feature-tag.poe {
    background: #1e3a29;
    color: #4ade80;
  }

  .feature-tag.managed {
    background: #1e3a5f;
    color: #60a5fa;
  }
}
</style>
