<script setup lang="ts">
import { ref, computed } from 'vue'
import QuoteSelectionBoard from '~/components/policies/QuoteSelectionBoard.vue'
import ConfirmAcceptModal from '~/components/policies/ConfirmAcceptModal.vue'

definePageMeta({ ssr: false })

const route = useRoute()
const policyId = route.params.id as string

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

usePageTitle(computed(() => `Policy ${policyId}`))

const { $policy } = useNuxtApp()
const toast = useToast()

// Formatting helpers
function formatDate(date: string) {
  if (!date) return '—'
  return new Date(date).toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })
}

function statusColor(status: string) {
  switch (status) {
    case 'quote_requested': return 'yellow'
    case 'quotes_received': return 'blue'
    case 'awaiting_policy': 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 'awaiting_policy': return 'Awaiting Policy'
    case 'issued': return 'Issued'
    default: return status
  }
}

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.insured_object
  if (!d || typeof d !== 'object') return '—'
  if (p.policy_type === 'car') {
    const parts = [d.year, d.make, d.model].filter((x: any) => 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 '—'
}

// Transform quotes to plan items
const planItems = computed(() => {
  const quotes = policy.value?.quotes || {}
  return Object.entries(quotes).flatMap(([provider_id, quote]: [string, any]) => {
    return (quote.plans || []).map(plan => ({
      provider_id,
      quote_id: quote.quote_id,
      valid_until: quote.valid_until,
      received_at: quote.received_at,
      plan_id: plan.plan_id,
      name: plan.name,
      premium: plan.premium,
      coverage_details: plan.coverage_details,
      deductible: plan.deductible,
      coverage_limit: plan.coverage_limit
    }))
  })
})

// Tabs state
const activeTab = ref('details')

// Modal state
const isConfirmModalOpen = ref(false)
const confirmModalPlanId = ref<string | null>(null)
const submitting = ref(false)

const selectedPlan = computed(() => {
  if (!confirmModalPlanId.value) return null
  return planItems.value.find(p => p.plan_id === confirmModalPlanId.value)
})

function openConfirmModal(planId: string) {
  confirmModalPlanId.value = planId
  isConfirmModalOpen.value = true
}

function closeConfirmModal() {
  isConfirmModalOpen.value = false
  confirmModalPlanId.value = null
}

async function confirmSelection() {
  if (!confirmModalPlanId.value) return
  const applicationId = policy.value?.application_id
  if (!applicationId) return

  submitting.value = true
  try {
    await $policy(`/policies/${applicationId}/accept`, {
      method: 'POST',
      body: { accepted_plan_id: confirmModalPlanId.value }
    })
    toast.add({ title: 'Quote accepted', color: 'green' })
    closeConfirmModal()
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed to accept quote', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="cp-page mx-auto max-w-6xl pb-12">
    <!-- Back link -->
    <NuxtLink to="/policies" class="inline-flex">
      <UButton color="neutral" variant="ghost" size="sm" icon="i-heroicons-arrow-left">Policies</UButton>
    </NuxtLink>

    <!-- Loading -->
    <div v-if="pending" class="flex items-center justify-center py-16">
      <UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin text-gray-400" />
    </div>

    <!-- Policy content -->
    <template v-else-if="policy">
      <!-- Header -->
      <div class="cp-header">
        <div class="cp-header-left">
          <div class="cp-avatar">{{ policyApplicantName(policy)[0] || '?' }}</div>
          <div class="cp-header-info">
            <div class="cp-header-name-row">
              <h1 class="cp-name">{{ policyApplicantName(policy) }}</h1>
              <span class="cp-type-badge capitalize">{{ policy.policy_type }}</span>
              <span class="cp-status-badge" :class="`pol-status-${statusColor(policy.status)}`">{{ statusLabel(policy.status) }}</span>
            </div>
            <div class="cp-header-meta">
              <span>Application ID: {{ policy.application_id }}</span>
              <span class="cp-sep" />
              <span>Submitted: {{ formatDate(policy.submitted_at) }}</span>
            </div>
          </div>
        </div>
        <div class="cp-header-actions">
          <UButton size="sm" color="neutral" variant="outline" icon="i-heroicons-pencil-square">Edit</UButton>
        </div>
      </div>

      <div class="cp-main-grid">
        <!-- Applicant Details -->
        <div class="cp-card cp-details-col">
          <div class="cp-card-head">
            <UIcon name="i-heroicons-user" style="width: 16px; height: 16px; color: #01696f;" />
            <span>Applicant Details</span>
          </div>
          <div class="cp-detail-list">
            <div class="cp-detail-row">
              <span class="cp-detail-label">Name</span>
              <span class="cp-detail-value">{{ policyApplicantName(policy) }}</span>
            </div>
            <div class="cp-detail-row">
              <span class="cp-detail-label">Document</span>
              <span class="cp-detail-value cp-mono">{{ policyApplicantDoc(policy) }}</span>
            </div>
            <div class="cp-detail-row">
              <span class="cp-detail-label">Email</span>
              <span class="cp-detail-value">{{ policy.insured?.email || '—' }}</span>
            </div>
            <div class="cp-detail-row">
              <span class="cp-detail-label">Phone</span>
              <span class="cp-detail-value">{{ policy.insured?.phone || '—' }}</span>
            </div>
            <div class="cp-detail-row">
              <span class="cp-detail-label">Address</span>
              <span class="cp-detail-value">{{ policy.insured?.address || '—' }}</span>
            </div>
          </div>
        </div>

        <!-- Right Column (Tabs) -->
        <div class="cp-tabbed-col">
          <div class="cp-tabs">
            <button type="button" class="cp-tab" :class="activeTab === 'details' ? 'cp-tab-on' : 'cp-tab-off'" @click="activeTab = 'details'">Details</button>
            <button type="button" class="cp-tab" :class="activeTab === 'quotes' ? 'cp-tab-on' : 'cp-tab-off'" @click="activeTab = 'quotes'">
              Quotes
              <span class="cp-tab-count" :class="activeTab === 'quotes' ? 'cp-tab-count-on' : ''">{{ Object.keys(policy.quotes ?? {}).length }}</span>
            </button>
          </div>

          <!-- Details Tab -->
          <div v-if="activeTab === 'details'" class="cp-tab-content">
            <div class="cp-card">
              <div class="cp-card-head">
                <UIcon name="i-heroicons-information-circle" style="width: 16px; height: 16px; color: #01696f;" />
                <span>Policy Information</span>
              </div>
              <div class="p-4 text-sm text-gray-600">
                <div class="space-y-2">
                  <div class="flex justify-between">
                    <span class="text-gray-500">Type</span>
                    <span class="font-medium capitalize">{{ policy.policy_type }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500">Status</span>
                    <span class="font-medium">{{ statusLabel(policy.status) }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500">Submitted</span>
                    <span class="font-medium">{{ formatDate(policy.submitted_at) }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500">Details</span>
                    <span class="font-medium">{{ policyDetailsSummary(policy) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Quotes Tab -->
          <div v-if="activeTab === 'quotes'" class="cp-tab-content">
            <div v-if="planItems.length > 0" class="cp-card p-4">
              <QuoteSelectionBoard
                :items="planItems"
                :selected-plan-id="policy?.accepted_plan_id || null"
                :policy-application-id="policy?.application_id || ''"
                @select="openConfirmModal"
              />
            </div>
            <p v-else class="cp-empty-msg">No quotes received yet</p>
          </div>
        </div>
      </div>

      <!-- Modal -->
      <ConfirmAcceptModal
        v-model:open="isConfirmModalOpen"
        :plan="selectedPlan"
        :loading="submitting"
        @accept="confirmSelection"
        @cancel="closeConfirmModal"
      />
    </template>

    <!-- Not found -->
    <div v-else class="flex items-center justify-center py-16">
      <div class="text-center">
        <UIcon name="i-heroicons-exclamation-triangle" class="w-12 h-12 mx-auto mb-4 text-gray-400" />
        <p class="text-lg font-medium text-gray-600">Policy not found</p>
        <NuxtLink to="/policies">
          <UButton color="neutral" variant="ghost" class="mt-4">Back to Policies</UButton>
        </NuxtLink>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cp-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-top: 8px;
}

.cp-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
}
.cp-header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}
.cp-header-info {
  min-width: 0;
}
.cp-avatar {
  width: 52px;
  height: 52px;
  border-radius: 12px;
  background: rgba(1, 105, 111, 0.08);
  color: #01696f;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 17px;
  font-weight: 600;
  flex-shrink: 0;
}
.cp-header-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.cp-name {
  font-size: 20px;
  font-weight: 600;
  letter-spacing: -0.01em;
  color: var(--text-primary);
}
.cp-type-badge {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 6px;
  background: rgba(1, 105, 111, 0.06);
  color: #01696f;
}
.cp-status-badge {
  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; }
.cp-header-meta {
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--text-muted);
}
.cp-sep {
  width: 3px;
  height: 3px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.15);
  flex-shrink: 0;
}
.cp-header-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  align-items: center;
}

.cp-card {
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  overflow: hidden;
}
.cp-card-head {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
}

.cp-main-grid {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 20px;
}

.cp-detail-list {
  padding: 16px 20px;
}
.cp-detail-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}
.cp-detail-row:last-child {
  border-bottom: none;
}
.cp-detail-label {
  font-size: 13px;
  color: var(--text-muted);
}
.cp-detail-value {
  font-size: 13px;
  color: var(--text-primary);
  font-weight: 500;
}
.cp-mono {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}

.cp-tabbed-col {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cp-tabs {
  display: flex;
  gap: 4px;
  padding: 4px;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 10px;
}
.cp-tab {
  flex: 1;
  padding: 8px 16px;
  font-size: 13px;
  font-weight: 500;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}
.cp-tab-on {
  background: #fff;
  color: var(--text-primary);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.cp-tab-off {
  background: transparent;
  color: #8a8a86;
}
.cp-tab-off:hover {
  color: var(--text-primary);
}
.cp-tab-count {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 9999px;
  background: rgba(0, 0, 0, 0.06);
  color: #8a8a86;
}
.cp-tab-count-on {
  background: rgba(1, 105, 111, 0.1);
  color: #01696f;
}

.cp-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cp-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
  transition: background 0.1s ease;
}
.cp-row:last-child {
  border-bottom: none;
}
.cp-row:hover {
  background: rgba(0, 0, 0, 0.015);
}
.cp-row-main {
  flex: 1;
  min-width: 0;
}
.cp-row-top {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}
.cp-row-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}
.cp-row-sub {
  font-size: 12px;
  color: var(--text-muted);
}
.cp-status {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 6px;
  white-space: nowrap;
}
.cp-status-ok {
  background: rgba(16, 185, 129, 0.1);
  color: #059669;
}

.cp-empty-msg {
  text-align: center;
  padding: 32px 16px;
  color: #9ca3af;
  font-size: 14px;
}
</style>
