<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, TicketTag, Department } from '@/types'

interface StaffUser {
  id: number
  name: string
}

interface Filters {
  search: string
  status: string
  priority: string
  department: string
  assigned_to: string
  tags: string
  sla_breached: boolean
}

interface Props {
  tickets: PaginatedResponse<SupportTicket>
  filters: Filters
  tags: TicketTag[]
  staffUsers: StaffUser[]
  departments: Department[]
}

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 assignedTo = ref<string>(props.filters.assigned_to)
const selectedTags = ref<string>(props.filters.tags)
const slaBreached = ref<boolean>(props.filters.sla_breached)

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: '' },
  ...props.departments.map(d => ({ title: d.name, value: d.slug })),
]

const staffOptions = [
  { title: 'All Staff', value: '' },
  ...props.staffUsers.map(u => ({ title: u.name, value: String(u.id) })),
]

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,
    assigned_to: assignedTo.value || undefined,
    tags: selectedTags.value || undefined,
    sla_breached: slaBreached.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

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

watch([status, priority, department, assignedTo, selectedTags, slaBreached], () => {
  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' })
}

function hasSlaBreach(ticket: SupportTicket): boolean {
  return ticket.sla_first_response_breached || ticket.sla_resolution_breached
}
</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="3">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by subject, customer..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="2">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
          <VCol cols="12" md="2">
            <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>
          <VCol cols="12" md="2">
            <VSelect
              v-model="assignedTo"
              :items="staffOptions"
              density="compact"
              hide-details
              label="Assigned To"
            />
          </VCol>
          <VCol cols="12" md="1">
            <VCheckbox
              v-model="slaBreached"
              label="SLA Breach"
              density="compact"
              hide-details
              color="error"
            />
          </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>Assigned To</th>
            <th>SLA</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>
              <template v-if="ticket.tags && ticket.tags.length > 0">
                <VChip
                  v-for="tag in ticket.tags"
                  :key="tag.id"
                  size="x-small"
                  :color="tag.color"
                  variant="tonal"
                  class="ms-1"
                >
                  {{ tag.name }}
                </VChip>
              </template>
            </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_relation?.name ?? ticket.department }}
            </td>
            <td class="text-body-2">
              {{ ticket.assignee?.name ?? 'Unassigned' }}
            </td>
            <td class="text-center">
              <VIcon
                v-if="hasSlaBreach(ticket)"
                icon="tabler-alert-triangle"
                size="20"
                color="error"
              >
                <VTooltip activator="parent" location="top">
                  SLA Breached
                </VTooltip>
              </VIcon>
              <VIcon
                v-else-if="ticket.sla_policy_id"
                icon="tabler-clock-check"
                size="20"
                color="success"
              >
                <VTooltip activator="parent" location="top">
                  SLA On Track
                </VTooltip>
              </VIcon>
              <span v-else class="text-medium-emphasis">-</span>
            </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>
