<template>
  <div class="detail-page">
    <div class="page-header">
      <h2>USB Device Details</h2>
      <div class="header-actions">
        <router-link to="/usb" class="btn btn-secondary">Back to List</router-link>
      </div>
    </div>

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

    <template v-else-if="device">
      <!-- Hero Section -->
      <div class="hero-card">
        <div class="hero-content">
          <div class="hero-title">
            <h1>{{ device.alias || device.machinenumber }}</h1>
          </div>
          <div class="hero-meta">
            <span class="badge badge-lg" :class="device.ischeckedout ? 'badge-warning' : 'badge-success'">
              {{ device.ischeckedout ? 'Checked Out' : 'Available' }}
            </span>
          </div>
          <div class="hero-details">
            <div class="hero-detail" v-if="device.serialnumber">
              <span class="hero-detail-label">Serial Number</span>
              <span class="hero-detail-value mono">{{ device.serialnumber }}</span>
            </div>
            <div class="hero-detail" v-if="device.vendorname">
              <span class="hero-detail-label">Vendor</span>
              <span class="hero-detail-value">{{ device.vendorname }}</span>
            </div>
            <div class="hero-detail" v-if="device.modelname">
              <span class="hero-detail-label">Model</span>
              <span class="hero-detail-value">{{ device.modelname }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Action Buttons -->
      <div class="action-buttons">
        <button
          v-if="!device.ischeckedout"
          class="btn btn-primary btn-lg"
          @click="openCheckoutModal"
        >
          Checkout Device
        </button>
        <button
          v-else
          class="btn btn-warning btn-lg"
          @click="openCheckinModal"
        >
          Check In Device
        </button>
      </div>

      <!-- Current Checkout Info -->
      <div class="section-card" v-if="device.currentcheckout">
        <h3 class="section-title">Current Checkout</h3>
        <div class="info-list">
          <div class="info-row">
            <span class="info-label">Checked Out By</span>
            <span class="info-value">{{ device.currentcheckout.sso }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">Checkout Time</span>
            <span class="info-value">{{ formatDate(device.currentcheckout.checkouttime) }}</span>
          </div>
          <div class="info-row" v-if="device.currentcheckout.checkoutreason">
            <span class="info-label">Reason</span>
            <span class="info-value">{{ device.currentcheckout.checkoutreason }}</span>
          </div>
        </div>
      </div>

      <!-- Checkout History -->
      <div class="card">
        <div class="card-header">
          <h3>Checkout History</h3>
        </div>

        <div v-if="!device.checkouthistory?.length" class="empty-state">
          No checkout history
        </div>

        <div v-else class="table-container">
          <table>
            <thead>
              <tr>
                <th>User SSO</th>
                <th>Checkout Time</th>
                <th>Check-in Time</th>
                <th>Wiped</th>
                <th>Reason</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="checkout in device.checkouthistory" :key="checkout.checkoutid">
                <td>{{ checkout.sso }}</td>
                <td>{{ formatDate(checkout.checkouttime) }}</td>
                <td>{{ checkout.checkintime ? formatDate(checkout.checkintime) : 'Still out' }}</td>
                <td>
                  <span v-if="checkout.checkintime">{{ checkout.waswiped ? 'Yes' : 'No' }}</span>
                  <span v-else>-</span>
                </td>
                <td>{{ checkout.checkoutreason || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </template>

    <div v-else class="card">
      <p style="text-align: center; color: var(--text-light);">USB device not found</p>
    </div>

    <!-- Checkout Modal -->
    <Modal v-if="showCheckoutModal" @close="closeModals">
      <template #header>
        <h3>Checkout USB Device</h3>
      </template>
      <template #body>
        <div class="form-group">
          <label>Your SSO *</label>
          <input v-model="checkoutForm.sso" type="text" class="form-control" placeholder="Enter your SSO" />
        </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>
      <template #footer>
        <button class="btn btn-secondary" @click="closeModals">Cancel</button>
        <button class="btn btn-primary" @click="doCheckout" :disabled="!checkoutForm.sso">Checkout</button>
      </template>
    </Modal>

    <!-- Checkin Modal -->
    <Modal v-if="showCheckinModal" @close="closeModals">
      <template #header>
        <h3>Check In USB Device</h3>
      </template>
      <template #body>
        <div class="form-group">
          <label class="checkbox-label">
            <input type="checkbox" v-model="checkinForm.waswiped" />
            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>
      <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 { useRoute } from 'vue-router'
import { usbApi } from '../../api'
import Modal from '../../components/Modal.vue'
import { useToast } from '../../composables/toast'
import { apiError } from '../../utils/apiError'
const toast = useToast()

const route = useRoute()

const loading = ref(true)
const device = ref(null)

const showCheckoutModal = ref(false)
const showCheckinModal = ref(false)
const checkoutForm = ref({ sso: '', reason: '' })
const checkinForm = ref({ waswiped: false, notes: '' })

onMounted(async () => {
  await loadDevice()
})

async function loadDevice() {
  loading.value = true
  try {
    const response = await usbApi.get(route.params.id)
    device.value = response.data.data
  } catch (error) {
    console.error('Error loading USB device:', error)
  } finally {
    loading.value = false
  }
}

function openCheckoutModal() {
  checkoutForm.value = { sso: '', reason: '' }
  showCheckoutModal.value = true
}

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

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

async function doCheckout() {
  try {
    await usbApi.checkout(device.value.machineid, checkoutForm.value)
    closeModals()
    await loadDevice()
  } catch (error) {
    console.error('Checkout error:', error)
    toast.error(apiError(error, 'Checkout failed'))
  }
}

async function doCheckin() {
  try {
    await usbApi.checkin(device.value.machineid, checkinForm.value)
    closeModals()
    await loadDevice()
  } catch (error) {
    console.error('Checkin error:', error)
    toast.error(apiError(error, 'Check in failed'))
  }
}

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

<style scoped>
.action-buttons {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.btn-lg {
  padding: 0.75rem 1.5rem;
  font-size: 1.125rem;
}

.empty-state {
  text-align: center;
  color: var(--text-light);
  padding: 2rem;
}

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

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

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

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

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