<script setup lang="ts">
usePageTitle('Policies')

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

const statusItems = [
  { label: 'All Statuses', value: null },
  { label: 'Quote Requested', value: 'quote_requested' },
  { label: 'Quotes Received', value: 'quotes_received' },
  { label: 'Solicitation Sent', value: 'solicitation_sent' },
  { label: 'Issued', value: 'issued' }
]

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

const { data, pending, refresh } = usePolicy('/policies', {
  query: computed(() => {
    const filters: Record<string, string> = {}
    let i = 0

    if (statusFilter.value) {
      filters[`filters[${i}][field]`] = 'status'
      filters[`filters[${i}][op]`] = '=='
      filters[`filters[${i}][value]`] = statusFilter.value
      i++
    }

    if (debouncedSearch.value) {
      filters[`filters[${i}][field]`] = 'search'
      filters[`filters[${i}][op]`] = '=='
      filters[`filters[${i}][value]`] = debouncedSearch.value
      i++
    }

    return {
      'page_size': 20,
      'page': page.value,
      ...filters
    }
  })
})

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

function policyApplicantName(p: any) {
  const info = p.insured
  if (!info || typeof info !== 'object') return '—'
  if (info.type === 'corporate') {
    return info.company_name || '—'
  }
  return info.name || '—'
}

function policyApplicantDoc(p: any) {
  const info = p.insured
  if (!info || typeof info !== 'object') return '—'
  if (info.type === 'corporate') {
    return info.ruc || '—'
  }
  return info.document_id || '—'
}

function policyDetailsSummary(p: any) {
  const d = p.policy_details
  if (!d || typeof d !== 'object') return '—'
  if (p.policy_type === 'car') {
    const parts = [d.year, d.make, d.model].filter((x: any) => x !== undefined && x !== null && String(x) !== '')
    return parts.length ? parts.map(String).join(' ') : '—'
  }
  if (p.policy_type === 'life') {
    return `Life · ${d.coverage_amount || 0} USD`
  }
  if (p.policy_type === 'fire_structure' || p.policy_type === 'fire_contents') {
    return d.location || '—'
  }
  return '—'
}

function statusColor(status: string) {
  switch (status) {
    case 'quote_requested': return 'yellow'
    case 'quotes_received': return 'blue'
    case 'solicitation_sent': return 'purple'
    case 'issued': return 'green'
    default: return 'gray'
  }
}

function statusLabel(status: string) {
  switch (status) {
    case 'quote_requested': return 'Quote Requested'
    case 'quotes_received': return 'Quotes Received'
    case 'solicitation_sent': return 'Solicitation Sent'
    case 'issued': return 'Issued'
    default: return status
  }
}

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

<template>
  <div class="pol-root mx-auto max-w-7xl pb-12">
    <div class="pol-header">
      <div class="pol-header-left">
        <h1 class="pol-title">Policies</h1>
        <span class="pol-count-badge">{{ meta?.total_count ?? 0 }}</span>
      </div>
      <div class="pol-header-right">
        <NuxtLink to="/policies/book">
          <button class="pol-btn-secondary">
            <UIcon name="i-heroicons-book-open" class="w-3.5 h-3.5" />
            Book of Business
          </button>
        </NuxtLink>
        <NuxtLink to="/quotes/new">
          <button class="pol-btn-primary">
            <UIcon name="i-heroicons-plus" class="w-3.5 h-3.5" />
            New Quote
          </button>
        </NuxtLink>
      </div>
    </div>

    <div class="pol-filter-bar">
      <div class="pol-search-wrap">
        <UIcon name="i-heroicons-magnifying-glass" class="pol-search-icon" />
        <input
          v-model="search"
          type="text"
          placeholder="Search by policy #, customer, carrier..."
          class="pol-search-input"
        />
      </div>
      <USelect v-model="statusFilter" :items="statusItems" class="pol-select" />
      <button class="pol-btn-ghost" :disabled="pending" @click="refresh()">
        <UIcon name="i-heroicons-arrow-path" class="w-3.5 h-3.5" :class="{ 'animate-spin': pending }" />
        Refresh
      </button>
    </div>

    <div v-if="pending" class="pol-card">
      <div style="padding: 20px;">
        <div v-for="n in 8" :key="n" class="pol-skeleton-row">
          <div class="pol-skeleton" style="width: 80px; height: 12px;" />
          <div class="pol-skeleton" style="width: 140px; height: 12px;" />
          <div class="pol-skeleton" style="width: 50px; height: 18px; border-radius: 10px;" />
          <div class="pol-skeleton" style="width: 100px; height: 12px;" />
          <div class="pol-skeleton" style="width: 100px; height: 12px;" />
          <div class="pol-skeleton" style="width: 70px; height: 12px;" />
          <div class="pol-skeleton" style="width: 50px; height: 18px; border-radius: 10px;" />
          <div class="pol-skeleton" style="width: 80px; height: 12px;" />
          <div class="pol-skeleton" style="width: 60px; height: 12px;" />
        </div>
      </div>
    </div>

    <template v-else>
      <div class="pol-card pol-card-flush">
        <div class="pol-card-head">
          <span>Policies</span>
          <span class="pol-card-head-count">{{ meta?.total_count ?? policies.length }}</span>
        </div>
        <div class="pol-table-wrap">
          <table class="pol-table">
            <thead>
              <tr>
                <th class="pol-th">Applicant</th>
                <th class="pol-th">Document</th>
                <th class="pol-th">Type</th>
                <th class="pol-th">Details</th>
                <th class="pol-th">Status</th>
                <th class="pol-th">Quotes</th>
                <th class="pol-th">Submitted</th>
              </tr>
            </thead>
            <tbody>
              <NuxtLink
                v-for="policy in policies"
                :key="policy.application_id"
                :to="`/policies/${policy.application_id}`"
                custom
                v-slot="{ navigate }"
              >
                <tr class="pol-row" style="cursor: pointer;" @click="navigate">
                  <td class="pol-td">
                    <p class="pol-product-name">{{ policyApplicantName(policy) }}</p>
                  </td>
                  <td class="pol-td">
                    <span class="pol-policy-number">{{ policyApplicantDoc(policy) }}</span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-carrier capitalize">{{ policy.policy_type }}</span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-carrier">
                      {{ policyDetailsSummary(policy) }}
                    </span>
                  </td>
                  <td class="pol-td">
                    <span
                      class="pol-status-badge"
                      :class="`pol-status-${statusColor(policy.status)}`"
                    >{{ statusLabel(policy.status) }}</span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-carrier">
                      {{ Object.keys(policy.quotes ?? {}).length }} / {{ (policy.selected_providers ?? []).length }}
                    </span>
                  </td>
                  <td class="pol-td">
                    <span class="pol-renewal-date">{{ new Date(policy.submitted_at).toLocaleDateString('es-PA') }}</span>
                  </td>
                </tr>
              </NuxtLink>
            </tbody>
          </table>
        </div>

        <div v-if="policies.length === 0" class="pol-empty">
          <UIcon name="i-heroicons-document-text" class="w-10 h-10" style="color: #8a8a86; opacity: 0.5;" />
          <p class="pol-empty-title">No policies found</p>
          <p class="pol-empty-sub">Create a new policy or adjust your filters</p>
        </div>
      </div>

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

<style scoped>
.pol-root {
  --pol-brand: #01696f;
  --pol-brand-soft: rgba(1, 105, 111, 0.06);
  --pol-border: rgba(0, 0, 0, 0.06);
  --pol-border-strong: rgba(0, 0, 0, 0.08);
  --pol-muted: #8a8a86;
  --pol-surface: #ffffff;
}

.pol-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pol-header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}
.pol-title {
  font-size: 24px;
  font-weight: 600;
  letter-spacing: -0.01em;
  color: var(--text-primary, #1a1a1a);
  line-height: 1;
}
.pol-count-badge {
  font-size: 11px;
  font-weight: 700;
  color: #01696f;
  background: rgba(1, 105, 111, 0.08);
  padding: 2px 9px;
  border-radius: 10px;
  letter-spacing: 0.01em;
}
.pol-header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pol-filter-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.pol-card {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
}
.pol-card-flush {
  overflow: hidden;
}
.pol-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.pol-card-head-count {
  font-size: 11px;
  font-weight: 600;
  color: #8a8a86;
  background: rgba(0, 0, 0, 0.04);
  padding: 2px 8px;
  border-radius: 10px;
}

.pol-btn-primary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  font-size: 12px;
  font-weight: 600;
  color: #ffffff;
  background: #01696f;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 150ms ease;
}
.pol-btn-primary:hover { background: #015258; }

.pol-btn-secondary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  cursor: pointer;
  transition: all 150ms ease;
}
.pol-btn-secondary:hover {
  border-color: rgba(1, 105, 111, 0.2);
  color: #01696f;
}

.pol-btn-ghost {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  font-size: 11px;
  font-weight: 500;
  color: #8a8a86;
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 6px;
  cursor: pointer;
  transition: all 150ms ease;
}
.pol-btn-ghost:hover { color: var(--text-primary, #1a1a1a); border-color: rgba(0, 0, 0, 0.12); }

.pol-search-wrap {
  position: relative;
  display: inline-flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
  max-width: 340px;
}
.pol-search-icon {
  position: absolute;
  left: 10px;
  width: 14px;
  height: 14px;
  color: #8a8a86;
  pointer-events: none;
}
.pol-search-input {
  padding: 6px 10px 6px 30px;
  width: 100%;
  font-size: 12px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  background: #ffffff;
  color: var(--text-primary, #1a1a1a);
  outline: none;
  transition: border-color 150ms ease;
}
.pol-search-input::placeholder { color: #8a8a86; }
.pol-search-input:focus { border-color: rgba(1, 105, 111, 0.3); }

.pol-select {
  appearance: none;
  padding: 6px 28px 6px 10px;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  font-size: 12px;
  font-weight: 500;
  color: var(--text-primary, #1a1a1a);
  background: #ffffff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%238a8a86'/%3E%3C/svg%3E") no-repeat right 10px center;
  cursor: pointer;
  outline: none;
  transition: border-color 150ms ease;
  white-space: nowrap;
}
.pol-select:focus { border-color: rgba(1, 105, 111, 0.3); }

.pol-table-wrap {
  overflow-x: auto;
}
.pol-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.pol-th {
  padding: 8px 12px;
  text-align: left;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: #8a8a86;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  white-space: nowrap;
}
.pol-td {
  padding: 8px 12px;
  vertical-align: middle;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
  font-size: 13px;
}
.pol-row {
  transition: background 120ms ease;
}
.pol-row:hover {
  background: rgba(0, 0, 0, 0.015);
}
.pol-row:last-child .pol-td {
  border-bottom: none;
}

.pol-policy-number {
  font-size: 12px;
  font-family: ui-monospace, 'SF Mono', 'Cascadia Mono', monospace;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-product-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
  line-height: 1.3;
}
.pol-carrier {
  font-size: 13px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}
.pol-renewal-date {
  font-size: 12px;
  color: var(--text-muted, #5c5650);
  white-space: nowrap;
}

.pol-status-badge {
  display: inline-block;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
}
.pol-status-yellow { background: rgba(245, 158, 11, 0.1); color: #d97706; }
.pol-status-blue { background: rgba(59, 130, 246, 0.1); color: #2563eb; }
.pol-status-purple { background: rgba(139, 92, 246, 0.1); color: #7c3aed; }
.pol-status-green { background: rgba(16, 185, 129, 0.1); color: #059669; }
.pol-status-gray { background: rgba(0, 0, 0, 0.05); color: #8a8a86; }

.pol-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48px 20px;
  text-align: center;
}
.pol-empty-title {
  margin-top: 12px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary, #1a1a1a);
}
.pol-empty-sub {
  margin-top: 4px;
  font-size: 12px;
  color: #8a8a86;
}

.pol-skeleton-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 10px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
}
.pol-skeleton-row:last-child { border-bottom: none; }
.pol-skeleton {
  height: 12px;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.05);
  animation: pol-pulse 1.5s ease-in-out infinite;
}
@keyframes pol-pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
