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

interface Filters {
  search: string
  category: string
}

interface Props {
  cannedResponses: PaginatedResponse<CannedResponseItem>
  categories: string[]
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const category = ref<string>(props.filters.category)

const categoryOptions = [
  { title: 'All Categories', value: '' },
  ...props.categories.map(c => ({ title: c, value: c })),
]

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

function applyFilters(): void {
  router.get('/canned-responses', {
    search: search.value || undefined,
    category: category.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

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

watch(category, () => {
  applyFilters()
})

function deleteResponse(id: number): void {
  if (confirm('Are you sure you want to delete this canned response?')) {
    router.delete(`/canned-responses/${id}`, { preserveScroll: true })
  }
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Canned Responses
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Pre-written responses for faster ticket replies
        </div>
      </div>
      <Link href="/canned-responses/create">
        <VBtn color="primary">
          <VIcon icon="tabler-plus" start />
          Create Response
        </VBtn>
      </Link>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="6">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by title or content..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VSelect
              v-model="category"
              :items="categoryOptions"
              density="compact"
              hide-details
              label="Category"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

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

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Title</th>
            <th>Category</th>
            <th>Shared</th>
            <th>Created By</th>
            <th>Usage Count</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="cr in cannedResponses.data" :key="cr.id">
            <td class="text-body-2 font-weight-medium">
              {{ cr.title }}
            </td>
            <td class="text-body-2">
              <VChip v-if="cr.category" size="small" variant="tonal">
                {{ cr.category }}
              </VChip>
              <span v-else class="text-medium-emphasis">-</span>
            </td>
            <td>
              <VChip :color="cr.is_shared ? 'success' : 'default'" size="small">
                {{ cr.is_shared ? 'Shared' : 'Private' }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ cr.creator?.name ?? 'Unknown' }}
            </td>
            <td class="text-body-2">
              {{ cr.usage_count }}
            </td>
            <td class="text-center">
              <Link :href="`/canned-responses/${cr.id}/edit`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-edit" size="18" />
                </VBtn>
              </Link>
              <VBtn variant="text" size="small" color="error" @click="deleteResponse(cr.id)">
                <VIcon icon="tabler-trash" size="18" />
              </VBtn>
            </td>
          </tr>
        </tbody>
      </VTable>

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