<template>
  <div>
    <div class="page-header">
      <h2>USB Devices</h2>
    </div>

    <!-- Filters -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search USB devices..."
        @input="debouncedSearch"
      />
      <label class="checkbox-label">
        <input type="checkbox" v-model="showAvailableOnly" @change="loadDevices" />
        Available Only
      </label>
    </div>

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

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Device</th>
                <th>Serial Number</th>
                <th>Status</th>
                <th>Checked Out By</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="device in devices" :key="device.machineid">
                <td>
                  <strong>{{ device.alias || device.machinenumber }}</strong>
                  <div v-if="device.model_name" class="text-muted">{{ device.model_name }}</div>
                </td>
                <td class="mono">{{ device.serialnumber || '-' }}</td>
                <td>
                  <span class="badge" :class="device.is_checked_out ? 'badge-warning' : 'badge-success'">
                    {{ device.is_checked_out ? 'Checked Out' : 'Available' }}
                  </span>
                </td>
                <td>
                  <template v-if="device.current_checkout">
                    {{ device.current_checkout.checkout_name || device.current_checkout.sso }}
                    <div class="text-muted">{{ formatDate(device.current_checkout.checkout_time) }}</div>
                  </template>
                  <span v-else>-</span>
                </td>
                <td class="actions">
                  <button
                    v-if="!device.is_checked_out"
                    class="btn btn-primary btn-sm"
                    @click="openCheckoutModal(device)"
                  >
                    Checkout
                  </button>
                  <button
                    v-else
                    class="btn btn-secondary btn-sm"
                    @click="openCheckinModal(device)"
                  >
                    Check In
                  </button>
                  <router-link
                    :to="`/usb/${device.machineid}`"
                    class="btn btn-secondary btn-sm"
                  >
                    View
                  </router-link>
                </td>
              </tr>
              <tr v-if="devices.length === 0">
                <td colspan="5" style="text-align: center; color: var(--text-light);">
                  No USB devices found
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div class="pagination" v-if="totalPages > 1">
          <button
            v-for="p in totalPages"
            :key="p"
            :class="{ active: p === page }"
            @click="goToPage(p)"
          >
            {{ p }}
          </button>
        </div>
      </template>
    </div>

    <!-- Checkout Modal -->
    <Modal v-model="showCheckoutModal" @close="closeModals">
      <template #header>
        <h3>Checkout USB Device</h3>
      </template>
      <p>Checking out: <strong>{{ selectedDevice?.alias || selectedDevice?.machinenumber }}</strong></p>
      <div class="form-group">
        <label>Employee *</label>
        <EmployeeSearch v-model="selectedEmployee" placeholder="Search by name..." />
      </div>
      <div class="form-group">
        <label>Reason</label>
        <textarea v-model="checkoutForm.reason" class="form-control" rows="3" placeholder="Why do you need this device?"></textarea>
      </div>
      <template #footer>
        <button class="btn btn-secondary" @click="closeModals">Cancel</button>
        <button class="btn btn-primary" @click="doCheckout" :disabled="!selectedEmployee">Checkout</button>
      </template>
    </Modal>

    <!-- Checkin Modal -->
    <Modal v-model="showCheckinModal" @close="closeModals">
      <template #header>
        <h3>Check In USB Device</h3>
      </template>
      <p>Checking in: <strong>{{ selectedDevice?.alias || selectedDevice?.machinenumber }}</strong></p>
      <div class="form-group">
        <label class="checkbox-label">
          <input type="checkbox" v-model="checkinForm.was_wiped" />
          Device was wiped
        </label>
      </div>
      <div class="form-group">
        <label>Notes</label>
        <textarea v-model="checkinForm.notes" class="form-control" rows="3" placeholder="Any notes about this return?"></textarea>
      </div>
      <template #footer>
        <button class="btn btn-secondary" @click="closeModals">Cancel</button>
        <button class="btn btn-primary" @click="doCheckin">Check In</button>
      </template>
    </Modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { usbApi } from '../../api'
import Modal from '../../components/Modal.vue'
import EmployeeSearch from '../../components/EmployeeSearch.vue'

const devices = ref([])
const loading = ref(true)
const search = ref('')
const page = ref(1)
const totalPages = ref(1)
const showAvailableOnly = ref(false)

const showCheckoutModal = ref(false)
const showCheckinModal = ref(false)
const selectedDevice = ref(null)
const checkoutForm = ref({ reason: '' })
const checkinForm = ref({ was_wiped: false, notes: '' })
const selectedEmployee = ref(null)

let searchTimeout = null

onMounted(() => {
  loadDevices()
})

async function loadDevices() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: 20
    }
    if (search.value) params.search = search.value
    if (showAvailableOnly.value) params.available = 'true'

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

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

function goToPage(p) {
  page.value = p
  loadDevices()
}

function openCheckoutModal(device) {
  selectedDevice.value = device
  checkoutForm.value = { reason: '' }
  selectedEmployee.value = null
  showCheckoutModal.value = true
}

function openCheckinModal(device) {
  selectedDevice.value = device
  checkinForm.value = { was_wiped: false, notes: '' }
  showCheckinModal.value = true
}

function closeModals() {
  showCheckoutModal.value = false
  showCheckinModal.value = false
  selectedDevice.value = null
  selectedEmployee.value = null
}

async function doCheckout() {
  if (!selectedEmployee.value) return

  try {
    await usbApi.checkout(selectedDevice.value.machineid, {
      sso: selectedEmployee.value.sso,
      name: selectedEmployee.value.name,
      reason: checkoutForm.value.reason
    })
    closeModals()
    loadDevices()
  } catch (error) {
    console.error('Checkout error:', error)
    alert(error.response?.data?.message || 'Checkout failed')
  }
}

async function doCheckin() {
  try {
    await usbApi.checkin(selectedDevice.value.machineid, checkinForm.value)
    closeModals()
    loadDevices()
  } catch (error) {
    console.error('Checkin error:', error)
    alert(error.response?.data?.message || 'Check in failed')
  }
}

function formatDate(dateStr) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString()
}
</script>

<style scoped>
.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
}

.text-muted {
  font-size: 0.875rem;
  color: var(--text-light);
}

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

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}
</style>
