<script setup lang="ts">
const route         = useRoute()
const applicationId = route.params.application_id as string

const { data, error, pending, refresh } = usePolicy(`/policies/${applicationId}`)
const policy = computed(() => data.value?.data)

// ── Accept plan ──────────────────────────────────────────────────────────────
const isAcceptOpen       = ref(false)
const accepting          = ref(false)
const selectedQuote      = ref<any>(null)
const selectedPlan       = ref<any>(null)
const solicitationFields = ref<Record<string, string>>({})
const toast              = useToast()
const { $policy }        = useNuxtApp()

function openAccept(quote: any, plan: any) {
  selectedQuote.value      = quote
  selectedPlan.value       = plan
  solicitationFields.value = {}
  isAcceptOpen.value       = true
}

async function submitAccept() {
  accepting.value = true
  try {
    await $policy(`/policies/${applicationId}/accept`, {
      method: 'POST',
      body: {
        quote_id:            selectedQuote.value.quote_id,
        plan_id:             selectedPlan.value.plan_id,
        solicitation_fields: solicitationFields.value
      }
    })
    toast.add({ title: 'Plan accepted — solicitation in progress', color: 'green' })
    isAcceptOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed to accept plan', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    accepting.value = false
  }
}

// ── Solicitation PDF ─────────────────────────────────────────────────────────
const solicitationUrl = ref<string | null>(null)
const loadingPdf      = ref(false)
const pdfError        = ref<string | null>(null)

async function loadSolicitationUrl() {
  if (!policy.value?.solicitation_id) return
  loadingPdf.value = true
  pdfError.value   = null
  try {
    const res = await $policy(`/car-policies/${applicationId}/solicitation-url`) as any
    solicitationUrl.value = res.download_url
  } catch (e: any) {
    pdfError.value = e?.data?.error ?? 'Failed to load document'
  } finally {
    loadingPdf.value = false
  }
}

watch(() => policy.value?.solicitation_id, (id) => {
  if (id) loadSolicitationUrl()
}, { immediate: true })

// ── Helpers ──────────────────────────────────────────────────────────────────
const quotes = computed(() => {
  if (!policy.value?.quotes) return []
  return Object.entries(policy.value.quotes).map(([provider_id, q]: [string, any]) => ({
    provider_id, ...q
  }))
})

const allPlans = computed(() =>
  quotes.value.flatMap((q: any) =>
    (q.plans ?? []).map((p: any) => ({
      ...p,
      provider_id: q.provider_id,
      valid_until: q.valid_until,
      quote_id:    q.quote_id
    }))
  )
)

const canAccept = computed(() => policy.value?.status === 'quotes_received')

const statusColor = (s: string) => ({
  quote_requested:   'yellow',
  quotes_received:   'blue',
  solicitation_sent: 'purple',
  active:            'green'
}[s] ?? 'gray')

const statusLabel = (s: string) => ({
  quote_requested:   'Quote Requested',
  quotes_received:   'Quotes Received',
  solicitation_sent: 'Solicitation Sent',
  active:            'Active'
}[s] ?? s)

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

const formatDate = (d: string) =>
  d ? new Date(d).toLocaleDateString('es-PA', { day: '2-digit', month: 'short', year: 'numeric' }) : '—'

const formatDateTime = (d: string) =>
  d ? new Date(d).toLocaleString('es-PA') : '—'

// ── Applicant display — handles both natural and juridico ────────────────────
const applicantRows = computed(() => {
  const info = policy.value?.applicant_info ?? {}
  const ct   = policy.value?.client_type

  if (ct === 'juridico') {
    return [
      { label: 'Company',       value: info.company_name ?? info['company_name'] },
      { label: 'RUC',           value: info.ruc ?? info['ruc'] },
      { label: 'Legal Rep',     value: info.legal_rep_name ?? info['legal_rep_name'] },
      { label: 'Rep Document',  value: info.legal_rep_document ?? info['legal_rep_document'] }
    ]
  }

  return [
    { label: 'Name',     value: info.name ?? info['name'] },
    { label: 'DOB',      value: formatDate(info.date_of_birth ?? info['date_of_birth']) },
    { label: 'Document', value: info.document_id ?? info['document_id'] }
  ]
})
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <NuxtLink to="/policies">
      <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">Back to Policies</UButton>
    </NuxtLink>

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

    <div v-else-if="pending" class="space-y-4">
      <UCard v-for="n in 4" :key="n"><div class="h-32 animate-pulse bg-gray-200 rounded" /></UCard>
    </div>

    <template v-else-if="policy">
      <!-- Header -->
      <div class="flex justify-between items-start">
        <div class="space-y-2">
          <div class="flex items-center gap-2">
            <UBadge :color="statusColor(policy.status)" variant="soft">
              {{ statusLabel(policy.status) }}
            </UBadge>
            <UBadge :color="clientTypeColor(policy.client_type)" variant="outline">
              {{ clientTypeLabel(policy.client_type) }}
            </UBadge>
            <UBadge color="gray" variant="outline">CAR</UBadge>
          </div>
          <h1 class="text-2xl font-bold text-slate-900">{{ policy.applicant_display_name }}</h1>
          <p class="text-gray-500 text-sm font-mono">{{ policy.application_id }}</p>
        </div>
        <UButton icon="i-heroicons-arrow-path" color="gray" variant="soft" :loading="pending" @click="refresh()" />
      </div>

      <!-- Info grid -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

        <!-- Applicant — dynamic rows based on client_type -->
        <UCard>
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-user" class="w-4 h-4" />
              {{ policy.client_type === 'juridico' ? 'Legal Entity' : 'Applicant' }}
              <UBadge :color="clientTypeColor(policy.client_type)" variant="soft" size="xs">
                {{ clientTypeLabel(policy.client_type) }}
              </UBadge>
            </p>
          </template>
          <div class="space-y-2 text-sm">
            <div v-for="row in applicantRows" :key="row.label" class="flex justify-between">
              <span class="text-gray-500">{{ row.label }}</span>
              <span class="font-medium font-mono text-xs">{{ row.value ?? '—' }}</span>
            </div>
          </div>
        </UCard>

        <!-- Vehicle -->
        <UCard>
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-truck" class="w-4 h-4" /> Vehicle
            </p>
          </template>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between"><span class="text-gray-500">Plate</span><span class="font-mono font-medium">{{ policy.plate }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Vehicle</span><span>{{ policy.year }} {{ policy.make }} {{ policy.model }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Value</span><span>${{ Number(policy.car_value).toLocaleString() }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Type</span><span class="capitalize">{{ policy.car_type }} / {{ policy.use_type }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Chassis</span><span class="font-mono text-xs">{{ policy.chassis_number }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Engine</span><span class="font-mono text-xs">{{ policy.engine_number }}</span></div>
          </div>
        </UCard>

        <!-- Issued policy -->
        <UCard v-if="policy.policy_number">
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-check-badge" class="w-4 h-4 text-green-500" /> Policy
            </p>
          </template>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between"><span class="text-gray-500">Policy #</span><span class="font-mono font-medium text-green-600">{{ policy.policy_number }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Premium</span><span class="font-semibold">${{ policy.premium }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Effective</span><span>{{ formatDate(policy.effective_date) }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Expires</span><span>{{ formatDate(policy.expiry_date) }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Issued</span><span>{{ formatDateTime(policy.issued_at) }}</span></div>
          </div>
        </UCard>

        <!-- Providers -->
        <UCard>
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-building-office" class="w-4 h-4" /> Providers
              <UBadge color="gray" variant="soft" size="xs">{{ policy.selected_providers?.length ?? 0 }}</UBadge>
            </p>
          </template>
          <div class="space-y-2">
            <div
              v-for="pid in policy.selected_providers" :key="pid"
              class="flex justify-between items-center text-sm p-2 bg-gray-50 rounded-lg"
            >
              <span class="font-mono text-xs text-gray-600">{{ pid }}</span>
              <UBadge :color="policy.quotes?.[pid] ? 'green' : 'yellow'" variant="soft" size="xs">
                {{ policy.quotes?.[pid] ? 'Quote received' : 'Pending' }}
              </UBadge>
            </div>
          </div>
        </UCard>
      </div>

      <!-- Quote comparison + accept -->
      <UCard v-if="quotes.length > 0">
        <template #header>
          <div class="flex justify-between items-center">
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-table-cells" class="w-4 h-4" /> Quote Comparison
              <UBadge color="gray" variant="soft" size="xs">{{ allPlans.length }} plans</UBadge>
            </p>
            <UBadge v-if="policy.accepted_plan_id" color="green" variant="soft">Plan Accepted</UBadge>
          </div>
        </template>

        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b">
                <th class="text-left py-3 px-4 text-gray-500 font-medium w-36">Feature</th>
                <th
                  v-for="plan in allPlans" :key="plan.plan_id"
                  class="py-3 px-4 text-center min-w-44"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''"
                >
                  <div class="space-y-1">
                    <UBadge v-if="plan.plan_id === policy.accepted_plan_id" color="green" variant="soft" size="xs">
                      Selected
                    </UBadge>
                    <p class="font-semibold text-slate-800">{{ plan.name }}</p>
                    <p class="text-xs font-mono text-gray-400">{{ plan.provider_id?.slice(0, 8) }}...</p>
                  </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr class="border-b bg-gray-50">
                <td class="py-3 px-4 font-medium text-gray-600">Premium</td>
                <td v-for="plan in allPlans" :key="plan.plan_id" class="py-3 px-4 text-center"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''">
                  <span class="font-bold text-lg text-slate-900">${{ Number(plan.premium).toLocaleString() }}</span>
                  <span class="text-xs text-gray-400 block">/year</span>
                </td>
              </tr>
              <tr class="border-b">
                <td class="py-3 px-4 font-medium text-gray-600">Deductible</td>
                <td v-for="plan in allPlans" :key="plan.plan_id" class="py-3 px-4 text-center"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''">
                  <span v-if="plan.deductible">${{ Number(plan.deductible).toLocaleString() }}</span>
                  <span v-else class="text-gray-400">—</span>
                </td>
              </tr>
              <tr class="border-b bg-gray-50">
                <td class="py-3 px-4 font-medium text-gray-600">Coverage Limit</td>
                <td v-for="plan in allPlans" :key="plan.plan_id" class="py-3 px-4 text-center"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''">
                  <span v-if="plan.coverage_limit">${{ Number(plan.coverage_limit).toLocaleString() }}</span>
                  <span v-else class="text-gray-400">—</span>
                </td>
              </tr>
              <tr class="border-b">
                <td class="py-3 px-4 font-medium text-gray-600">Valid Until</td>
                <td v-for="plan in allPlans" :key="plan.plan_id" class="py-3 px-4 text-center"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''">
                  {{ formatDate(plan.valid_until) }}
                </td>
              </tr>
              <tr class="border-b bg-gray-50">
                <td class="py-3 px-4 font-medium text-gray-600 align-top pt-4">Coverage</td>
                <td v-for="plan in allPlans" :key="plan.plan_id"
                  class="py-3 px-4 text-center align-top pt-4"
                  :class="plan.plan_id === policy.accepted_plan_id ? 'bg-green-50' : ''">
                  <div v-if="plan.coverage_details" class="space-y-1">
                    <div v-for="(value, key) in plan.coverage_details" :key="key" class="flex text-xs">
                      <span class="font-medium text-gray-500">{{ key }}:</span>
                      <span class="text-gray-700 ml-1">{{ value }}</span>
                    </div>
                  </div>
                  <div v-else class="text-gray-400 text-xs">—</div>
                </td>
              </tr>
              <!-- Accept row -->
              <tr v-if="canAccept">
                <td class="py-4 px-4" />
                <td v-for="plan in allPlans" :key="plan.plan_id" class="py-4 px-4 text-center">
                  <UButton
                    color="primary" size="sm" icon="i-heroicons-check"
                    @click="openAccept({ quote_id: plan.quote_id, provider_id: plan.provider_id, valid_until: plan.valid_until }, plan)"
                  >
                    Accept
                  </UButton>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </UCard>

      <!-- Solicitation PDF -->
      <UCard v-if="policy.solicitation_id">
        <template #header>
          <div class="flex justify-between items-center">
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-document-text" class="w-4 h-4" /> Solicitation Document
            </p>
            <div class="flex items-center gap-2">
              <UBadge color="purple" variant="soft" size="xs">{{ policy.solicitation_id?.slice(0, 8) }}...</UBadge>
              <UButton
                icon="i-heroicons-arrow-path" color="gray" variant="ghost" size="xs"
                :loading="loadingPdf" @click="loadSolicitationUrl()"
              >
                Refresh URL
              </UButton>
              <UButton
                v-if="solicitationUrl"
                icon="i-heroicons-arrow-top-right-on-square"
                color="gray" variant="soft" size="xs"
                :to="solicitationUrl" target="_blank"
              >
                Open
              </UButton>
            </div>
          </div>
        </template>

        <div v-if="loadingPdf" class="h-64 flex items-center justify-center text-gray-400">
          <UIcon name="i-heroicons-document-arrow-down" class="w-8 h-8 animate-pulse" />
        </div>
        <UAlert v-else-if="pdfError" color="red" variant="soft" :description="pdfError" />
        <iframe
          v-else-if="solicitationUrl"
          :src="solicitationUrl"
          class="w-full rounded-lg border"
          style="height: 600px;"
        />
        <div v-else class="h-32 flex items-center justify-center text-gray-400 text-sm">
          Solicitation not yet generated
        </div>
      </UCard>
    </template>

    <!-- Accept Slideover -->
    <USlideover v-model:open="isAcceptOpen" side="right">
      <template #content>
        <div class="flex flex-col h-full">
          <div class="flex justify-between items-center p-6 border-b">
            <div>
              <h2 class="text-lg font-semibold text-slate-900">Accept Plan</h2>
              <p v-if="selectedPlan" class="text-sm text-gray-500">
                {{ selectedPlan.name }} — ${{ Number(selectedPlan.premium).toLocaleString() }}/yr
              </p>
            </div>
            <UButton icon="i-heroicons-x-mark" color="gray" variant="ghost" @click="isAcceptOpen = false" />
          </div>

          <div class="flex-1 overflow-y-auto p-6 space-y-6">
            <!-- Plan summary -->
            <div v-if="selectedPlan" class="bg-primary-50 border border-primary-200 rounded-lg p-4 text-sm space-y-2">
              <div class="flex justify-between">
                <span class="text-primary-600">Plan</span>
                <span class="font-semibold">{{ selectedPlan.name }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-primary-600">Premium</span>
                <span class="font-bold text-primary-900">${{ Number(selectedPlan.premium).toLocaleString() }}/yr</span>
              </div>
              <div v-if="selectedPlan.deductible" class="flex justify-between">
                <span class="text-primary-600">Deductible</span>
                <span>${{ Number(selectedPlan.deductible).toLocaleString() }}</span>
              </div>
              <div v-if="selectedPlan.coverage_limit" class="flex justify-between">
                <span class="text-primary-600">Coverage Limit</span>
                <span>${{ Number(selectedPlan.coverage_limit).toLocaleString() }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-primary-600">Provider</span>
                <span class="font-mono text-xs">{{ selectedQuote?.provider_id?.slice(0, 12) }}...</span>
              </div>
            </div>

            <!-- Optional solicitation fields -->
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <p class="font-medium text-sm text-slate-700">Additional Fields</p>
                <UButton
                  icon="i-heroicons-plus" color="gray" variant="soft" size="xs"
                  @click="solicitationFields[`field_${Object.keys(solicitationFields).length + 1}`] = ''"
                >
                  Add Field
                </UButton>
              </div>
              <p class="text-xs text-gray-400">
                Optional provider-specific fields for the solicitation form.
              </p>
              <div v-for="(val, key) in solicitationFields" :key="key" class="flex gap-2 items-end">
                <UFormField :label="String(key)" class="flex-1">
                  <UInput v-model="solicitationFields[key]" class="w-full" />
                </UFormField>
                <UButton icon="i-heroicons-trash" color="red" variant="ghost" size="sm"
                  @click="delete solicitationFields[key]" />
              </div>
              <p v-if="Object.keys(solicitationFields).length === 0" class="text-xs text-gray-400 italic">
                No additional fields — the PDF will be filled from policy data automatically.
              </p>
            </div>
          </div>

          <div class="p-6 border-t flex justify-end gap-3">
            <UButton color="gray" variant="soft" @click="isAcceptOpen = false">Cancel</UButton>
            <UButton
              color="primary" icon="i-heroicons-check"
              :loading="accepting"
              @click="submitAccept"
            >
              Confirm & Generate Solicitation
            </UButton>
          </div>
        </div>
      </template>
    </USlideover>
  </div>
</template>
