<template>
  <div>
    <div class="page-header">
      <h2>Printers</h2>
      <div class="header-actions">
        <router-link to="/printer-installer" class="btn btn-secondary" target="_blank">Installer Map</router-link>
        <router-link to="/print/printer-qr" class="btn btn-secondary" target="_blank">Batch Print QR</router-link>
        <router-link to="/print/asset-label-batch/printer" class="btn btn-secondary" target="_blank">Print Labels</router-link>
        <router-link to="/printers/new" class="btn btn-primary">Add Printer</router-link>
      </div>
    </div>

    <!-- Filters -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search printers..."
        @input="debouncedSearch"
      />
      <select v-model="typeFilter" class="form-control" @change="onFilterChange">
        <option value="">All types</option>
        <option v-for="pt in printerTypes" :key="pt.printertypeid" :value="pt.printertypeid">
          {{ pt.printertype }}
        </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>Name</th>
                <th>Business Unit</th>
                <th>Type</th>
                <th>Model</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="printer in printers" :key="printer.printer?.printerid || printer.assetid" class="clickable-row" @click="$router.push(`/printers/${printer.printer?.printerid || printer.assetid}`)">
                <td>{{ printer.assetnumber }}</td>
                <td>{{ printer.name && printer.name.toUpperCase() !== 'NONE' ? printer.name : (printer.printer?.hostname || '-') }}</td>
                <td>{{ printer.businessunitname || '-' }}</td>
                <td>{{ printer.printer?.printertypename || '-' }}</td>
                <td>{{ printer.printer?.modelname || '-' }}</td>
                <td>
                  <span class="badge" :class="getStatusClass(printer.statusname)">
                    {{ printer.statusname || 'Active' }}
                  </span>
                </td>
                <td class="actions" @click.stop>
                  <router-link
                    :to="`/printers/${printer.printer?.printerid || printer.assetid}`"
                    class="btn btn-secondary btn-sm"
                  >
                    View
                  </router-link>
                </td>
              </tr>
              <tr v-if="printers.length === 0">
                <td colspan="7" style="text-align: center; color: var(--text-light);">
                  No printers found
                </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 { printersApi } from '@/api'
import PaginationBar from '@/components/PaginationBar.vue'
import { useListQuery } from '@/composables/listQuery'

const printers = ref([])
const printerTypes = ref([])
const typeFilter = ref('')
const loading = ref(true)
const { page, search, setPage, setSearch } = useListQuery({ onChange: loadPrinters })
const totalPages = ref(1)
const perPage = ref(20)

let searchTimeout = null

onMounted(async () => {
  try {
    const response = await printersApi.types.list({ perpage: 100 })
    printerTypes.value = response.data.data || []
  } catch (error) {
    console.error('Error loading printer types:', error)
  }
  loadPrinters()
})

async function loadPrinters() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: perPage.value
    }
    if (search.value) params.search = search.value
    if (typeFilter.value) params.typeid = typeFilter.value

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

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

function onFilterChange() {
  setPage(1)
  loadPrinters()
}

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

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

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') return 'badge-warning'
  if (s === 'retired') return 'badge-danger'
  return 'badge-info'
}
</script>
