<script setup lang="ts">
import { refDebounced } from '@vueuse/core'
import type { SelectItem } from '@nuxt/ui'

const page          = ref(1)
const search        = ref('')
const statusFilter  = ref<string | null>(null)
const debouncedSearch = refDebounced(search, 300)

const statusItems = ref<SelectItem[]>([
  { label: 'All Statuses',      value: null              },
  { label: 'Quote Requested',   value: 'quote_requested' },
  { label: 'Quotes Received',   value: 'quotes_received' },
  { label: 'Solicitation Sent', value: 'solicitation_sent' },
  { label: 'Active',            value: 'active'          }
])

watch(debouncedSearch, () => { page.value = 1 })
watch(statusFilter,    () => { page.value = 1 })

const { data, error, pending, refresh } = usePolicy('/car-policies', {
  query: computed(() => ({
    page_size: 20,
    page: page.value,
    ...(statusFilter.value && {
      'filters[0][field]': 'status',
      'filters[0][op]':    '==',
      'filters[0][value]': statusFilter.value
    }),
    ...(debouncedSearch.value && {
      [`filters[${statusFilter.value ? 1 : 0}][field]`]: 'search',
      [`filters[${statusFilter.value ? 1 : 0}][op]`]:    '==',
      [`filters[${statusFilter.value ? 1 : 0}][value]`]: debouncedSearch.value
    })
  }))
})

const policies = computed(() => data.value?.data ?? [])
const meta     = computed(() => data.value?.meta)

const statusColor = (status: string) => {
  switch (status) {
    case 'quote_requested':   return 'yellow'
    case 'quotes_received':   return 'blue'
    case 'solicitation_sent': return 'purple'
    case 'active':            return 'green'
    default:                  return 'gray'
  }
}

const statusLabel = (status: string) => {
  switch (status) {
    case 'quote_requested':   return 'Quote Requested'
    case 'quotes_received':   return 'Quotes Received'
    case 'solicitation_sent': return 'Solicitation Sent'
    case 'active':            return 'Active'
    default:                  return status
  }
}

const statusIcon = (status: string) => {
  switch (status) {
    case 'quote_requested':   return 'i-heroicons-clock'
    case 'quotes_received':   return 'i-heroicons-inbox'
    case 'solicitation_sent': return 'i-heroicons-paper-airplane'
    case 'active':            return 'i-heroicons-check-badge'
    default:                  return 'i-heroicons-document'
  }
}

const clientTypeLabel = (ct: string) =>
  ct === 'juridico' ? 'Jurídico' : 'Natural'

const clientTypeColor = (ct: string) =>
  ct === 'juridico' ? 'purple' : 'blue'
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <!-- Header -->
    <div class="flex justify-between items-center">
      <div>
        <h1 class="text-3xl text-slate-900 font-bold">Policies</h1>
        <p class="text-gray-500 text-sm">Car Insurance Policy Management</p>
      </div>
      <div class="flex items-center gap-3">
        <UBadge color="gray" variant="soft" size="lg">
          {{ meta?.total_count ?? 0 }} policies
        </UBadge>
        <NuxtLink to="/policies/new">
          <UButton icon="i-heroicons-plus" color="primary">New Policy</UButton>
        </NuxtLink>
      </div>
    </div>

    <!-- Filters -->
    <div class="flex gap-4 items-center flex-wrap">
      <UInput
        v-model="search"
        icon="i-heroicons-magnifying-glass"
        placeholder="Search by name, plate, policy #..."
        class="w-80"
      />
      <USelect v-model="statusFilter" :items="statusItems" class="w-52" />
      <UButton
        icon="i-heroicons-arrow-path"
        color="gray" variant="soft"
        :loading="pending"
        @click="refresh()"
      >
        Refresh
      </UButton>
    </div>

    <UAlert v-if="error" color="red" variant="soft" title="Failed to load policies" :description="error.message" />

    <div v-else-if="pending" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
      <UCard v-for="n in 6" :key="n">
        <div class="h-48 animate-pulse bg-gray-200 rounded" />
      </UCard>
    </div>

    <template v-else>
      <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <NuxtLink
          v-for="policy in policies"
          :key="policy.application_id"
          :to="`/policies/${policy.application_id}`"
        >
          <UCard class="hover:shadow-md transition-shadow cursor-pointer h-full">
            <div class="space-y-4">
              <!-- Status + type badges -->
              <div class="flex justify-between items-start">
                <UBadge :color="statusColor(policy.status)" variant="soft" class="flex items-center gap-1">
                  <UIcon :name="statusIcon(policy.status)" class="w-3 h-3" />
                  {{ statusLabel(policy.status) }}
                </UBadge>
                <div class="flex gap-1">
                  <UBadge :color="clientTypeColor(policy.client_type)" variant="outline" size="xs">
                    {{ clientTypeLabel(policy.client_type) }}
                  </UBadge>
                  <UBadge color="gray" variant="outline" size="xs">CAR</UBadge>
                </div>
              </div>

              <!-- Applicant -->
              <div>
                <p class="font-semibold text-slate-900 text-lg leading-tight">
                  {{ policy.applicant_display_name }}
                </p>
                <p class="text-gray-400 text-sm">{{ policy.applicant_document }}</p>
              </div>

              <!-- Vehicle -->
              <div class="bg-gray-50 rounded-lg p-3 space-y-1.5 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-500">Plate</span>
                  <span class="font-medium font-mono">{{ policy.plate }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">Vehicle</span>
                  <span class="font-medium">{{ policy.year }} {{ policy.make }} {{ policy.model }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">Value</span>
                  <span class="font-medium">${{ Number(policy.car_value).toLocaleString() }}</span>
                </div>
                <div v-if="policy.policy_number" class="flex justify-between">
                  <span class="text-gray-500">Policy #</span>
                  <span class="font-medium font-mono text-green-600">{{ policy.policy_number }}</span>
                </div>
              </div>

              <!-- Footer -->
              <div class="flex justify-between items-center text-xs text-gray-400 pt-1 border-t">
                <div class="flex items-center gap-1">
                  <UIcon name="i-heroicons-chat-bubble-left-right" class="w-3.5 h-3.5" />
                  <span>
                    {{ Object.keys(policy.quotes ?? {}).length }} /
                    {{ (policy.selected_providers ?? []).length }} quotes
                  </span>
                </div>
                <span>{{ new Date(policy.submitted_at).toLocaleDateString('es-PA') }}</span>
              </div>
            </div>
          </UCard>
        </NuxtLink>

        <div v-if="policies.length === 0" class="col-span-3 text-center py-16 text-gray-400">
          <UIcon name="i-heroicons-document-text" class="w-12 h-12 mx-auto mb-4" />
          <p class="text-lg font-medium">No policies found</p>
          <p class="text-sm">Create a new policy or adjust your filters</p>
        </div>
      </div>

      <!-- Pagination -->
      <div v-if="meta && meta.total_pages > 1" class="flex justify-center">
        <UPagination v-model="page" :total="meta.total_count" :page-count="meta.page_size" />
      </div>
    </template>
  </div>
</template>
