<script lang="ts" setup>
import { Link, router } from '@inertiajs/vue3'
import { ref, watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { resolveTicketStatusColor, resolveTicketPriorityColor } from '@/utils/resolvers'
import type { PaginatedResponse, SupportTicket } from '@/types'

interface Filters {
  search: string
  status: string
  priority: string
  department: string
}

interface Props {
  tickets: PaginatedResponse<SupportTicket>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const status = ref<string>(props.filters.status)
const priority = ref<string>(props.filters.priority)
const department = ref<string>(props.filters.department)

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Open', value: 'open' },
  { title: 'In Progress', value: 'in_progress' },
  { title: 'Waiting', value: 'waiting' },
  { title: 'Closed', value: 'closed' },
]

const priorityOptions = [
  { title: 'All Priorities', value: '' },
  { title: 'Low', value: 'low' },
  { title: 'Medium', value: 'medium' },
  { title: 'High', value: 'high' },
  { title: 'Urgent', value: 'urgent' },
]

const departmentOptions = [
  { title: 'All Departments', value: '' },
  { title: 'General', value: 'general' },
  { title: 'Billing', value: 'billing' },
  { title: 'Technical', value: 'technical' },
  { title: 'Sales', value: 'sales' },
]

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function applyFilters(): void {
  router.get('/tickets', {
    search: search.value || undefined,
    status: status.value || undefined,
    priority: priority.value || undefined,
    department: department.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

watch(search, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(applyFilters, 300)
})

watch([status, priority, department], () => {
  applyFilters()
})

function formatStatus(statusVal: string): string {
  return statusVal.replace(/_/g, ' ')
}

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Support Tickets
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage all customer support tickets
        </div>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="4">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by subject, customer name, or email..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VSelect
              v-model="priority"
              :items="priorityOptions"
              density="compact"
              hide-details
              label="Priority"
            />
          </VCol>
          <VCol cols="12" md="2">
            <VSelect
              v-model="department"
              :items="departmentOptions"
              density="compact"
              hide-details
              label="Department"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Tickets Table -->
    <VCard>
      <VCardText v-if="tickets.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-ticket-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No tickets found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>#</th>
            <th>Subject</th>
            <th>Customer</th>
            <th>Status</th>
            <th>Priority</th>
            <th>Department</th>
            <th>Last Updated</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="ticket in tickets.data" :key="ticket.id">
            <td class="text-body-2 text-medium-emphasis">
              {{ ticket.id }}
            </td>
            <td class="text-body-2 font-weight-medium">
              {{ ticket.subject }}
              <VChip
                v-if="ticket.ticket_reference"
                size="x-small"
                color="secondary"
                variant="tonal"
                class="ms-2"
              >
                {{ ticket.ticket_reference }}
              </VChip>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ ticket.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ ticket.user?.email ?? '' }}</span>
              </div>
            </td>
            <td>
              <VChip
                :color="resolveTicketStatusColor(ticket.status)"
                size="small"
                class="text-capitalize"
              >
                {{ formatStatus(ticket.status) }}
              </VChip>
            </td>
            <td>
              <VChip
                :color="resolveTicketPriorityColor(ticket.priority)"
                size="small"
                class="text-capitalize"
              >
                {{ ticket.priority }}
              </VChip>
            </td>
            <td class="text-body-2 text-capitalize">
              {{ ticket.department }}
            </td>
            <td class="text-body-2">
              {{ formatDate(ticket.updated_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/tickets/${ticket.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="tickets.last_page > 1" class="d-flex align-center justify-center pt-2">
        <VPagination
          :model-value="tickets.data.length > 0 ? Math.ceil((tickets.from ?? 1) / 25) : 1"
          :length="tickets.last_page"
          :total-visible="7"
          @update:model-value="(page: number) => router.get('/tickets', { ...props.filters, page }, { preserveState: true, preserveScroll: true })"
        />
      </VCardText>

      <VCardText v-if="tickets.total > 0" class="text-center text-caption text-medium-emphasis">
        Showing {{ tickets.from }} to {{ tickets.to }} of {{ tickets.total }} tickets
      </VCardText>
    </VCard>
  </div>
</template>
