<script setup lang="ts">
import {
  LIFE_COVERAGE_AMOUNT_OPTIONS,
  LIFE_COVERAGE_TERM_OPTIONS
} from '~/data/life-quote-intake'
import type { LifeQuoteDraft, LifeQuoteMode, LifeQuoteSegment } from '~/types/life-quote-intake'
import { useCustomerSelection } from '~/composables/useCustomerSelection'

const props = defineProps<{
  draft: LifeQuoteDraft
  modeCards: { id: LifeQuoteMode; title: string; hint: string; icon: string }[]
  segmentCards: { id: LifeQuoteSegment; title: string; hint: string; icon: string }[]
}>()

function setMode(m: LifeQuoteMode) {
  props.draft.quoteMode = m
}

function setSegment(s: LifeQuoteSegment) {
  props.draft.segment = s
}

const inputPh =
  'w-full placeholder:text-[var(--text-muted)] placeholder:opacity-[0.55] text-[var(--text-primary)]'

const showOrganization = computed(
  () => props.draft.segment === 'corporate_keyman' || props.draft.segment === 'group'
)

// Use customer selection composable
const {
  selectedCustomer,
  selectedBuyer,
  useSameForBuyer,
  insured,
  buyer,
  isInsuredValid,
  isBuyerValid,
  validationErrors
} = useCustomerSelection()

// Customer selection
const customerSearch = ref('')
const debouncedCustomerSearch = refDebounced(customerSearch, 300)
const customerPage = ref(1)

const { data: customersData, pending: customersPending } = useCustomer('/customers', {
  query: computed(() => ({
    'page[number]': customerPage.value,
    'page[size]': 12,
    ...(debouncedCustomerSearch.value && {
      'filters[0][field]': 'search',
      'filters[0][op]': '==',
      'filters[0][value]': debouncedCustomerSearch.value
    })
  }))
})

watch(debouncedCustomerSearch, () => { customerPage.value = 1 })

const customerItems = computed(() => customersData.value?.data ?? [])

function selectCustomer(customer: any) {
  selectedCustomer.value = customer
}

function selectBuyer(customer: any) {
  selectedBuyer.value = customer
}

const customerDisplayName = (c: any) =>
  c.customer_type === 'corporate'
    ? (c.commercial_name || c.legal_name)
    : `${c.first_name} ${c.last_name}`

const customerSubtitle = (c: any) =>
  c.customer_type === 'corporate' ? c.ruc : c.email

const showDetails = ref(false)
onMounted(() => {
  requestAnimationFrame(() => {
    showDetails.value = true
  })
})
</script>

<template>
  <div class="space-y-10">
    <section class="space-y-4">
      <div>
        <h3 class="text-base font-semibold text-[var(--text-primary)]">How can I help?</h3>
        <p class="mt-1 text-sm text-[var(--text-muted)]">Single quote or comparative PDF — same steps; comparative opens the comparison sheet after acceptance.</p>
      </div>
      <div class="grid gap-3 sm:grid-cols-2">
        <button
          v-for="card in modeCards"
          :key="card.id"
          type="button"
          class="group rounded-xl border p-5 text-left transition focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)]"
          :class="
            draft.quoteMode === card.id
              ? 'border-[var(--brand)] bg-[var(--brand-soft)] ring-1 ring-[var(--brand)]/30'
              : 'border-[var(--sidebar-border)] bg-[var(--surface)] hover:border-[var(--brand)]/40'
          "
          @click="setMode(card.id)"
        >
          <div class="flex items-start gap-3">
            <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-[var(--brand-faint)] text-[var(--brand)]">
              <UIcon :name="card.icon" class="h-5 w-5" />
            </div>
            <div class="min-w-0">
              <p class="font-semibold text-[var(--text-primary)]">{{ card.title }}</p>
              <p class="mt-1 text-sm text-[var(--text-muted)]">{{ card.hint }}</p>
            </div>
          </div>
        </button>
      </div>
    </section>

    <section class="space-y-4 border-t border-[var(--sidebar-border)] pt-10">
      <div>
        <h3 class="text-base font-semibold text-[var(--text-primary)]">Policy type</h3>
        <p class="mt-1 text-sm text-[var(--text-muted)]">Individual, corporate / key person, or group policy.</p>
      </div>
      <div class="grid gap-3 sm:grid-cols-3">
        <button
          v-for="card in segmentCards"
          :key="card.id"
          type="button"
          class="rounded-xl border p-4 text-left transition focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)]"
          :class="
            draft.segment === card.id
              ? 'border-[var(--brand)] bg-[var(--brand-soft)] ring-1 ring-[var(--brand)]/30'
              : 'border-[var(--sidebar-border)] bg-[var(--surface)] hover:border-[var(--brand)]/40'
          "
          @click="setSegment(card.id)"
        >
          <UIcon :name="card.icon" class="h-7 w-7 text-[var(--brand)]" />
          <p class="mt-2 font-semibold text-[var(--text-primary)]">{{ card.title }}</p>
          <p class="mt-0.5 text-xs text-[var(--text-muted)]">{{ card.hint }}</p>
        </button>
      </div>
    </section>

    <section v-if="showDetails" class="border-t border-[var(--sidebar-border)] pt-10">
      <!-- Insured Section -->
      <h3 class="text-base font-semibold text-[var(--text-primary)]">Insured</h3>
      <p class="mt-1 text-sm text-[var(--text-muted)]">Person or entity being insured — we'll use this for carrier notifications.</p>
      
      <div v-if="!selectedCustomer" class="mt-5">
        <UInput
          v-model="customerSearch"
          icon="i-heroicons-magnifying-glass"
          placeholder="Search by name, email, RUC..."
          class="w-full max-w-sm mb-4"
        />
        
        <div v-if="customersPending" class="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div v-for="n in 3" :key="n" class="h-16 animate-pulse bg-gray-100 rounded-lg" />
        </div>
        
        <div v-else class="space-y-3 max-h-72 overflow-y-auto">
          <div
            v-for="c in customerItems"
            :key="c.id"
            class="flex items-center gap-3 p-3 border-2 rounded-lg cursor-pointer transition-all"
            :class="selectedCustomer?.id === c.id
              ? 'border-primary-500 bg-primary-50'
              : 'border-gray-200 hover:border-gray-300 bg-white'"
            @click="selectCustomer(c)"
          >
            <UAvatar :alt="customerDisplayName(c)" size="sm" />
            <div class="min-w-0 flex-1">
              <div class="flex items-center gap-1.5">
                <p class="font-medium text-sm text-slate-800 truncate">{{ customerDisplayName(c) }}</p>
                <UBadge
                  :color="c.customer_type === 'corporate' ? 'purple' : 'blue'"
                  variant="soft" size="xs" class="flex-shrink-0"
                >
                  {{ c.customer_type === 'corporate' ? 'Corp' : 'Ind' }}
                </UBadge>
              </div>
              <p class="text-xs text-gray-400 truncate">{{ customerSubtitle(c) }}</p>
            </div>
            <UIcon
              v-if="selectedCustomer?.id === c.id"
              name="i-heroicons-check-circle"
              class="w-5 h-5 text-primary-500 flex-shrink-0"
            />
          </div>
          
          <div v-if="customerItems.length === 0" class="text-center py-6 text-gray-400 text-sm">
            No customers found.
          </div>
        </div>
      </div>
      
      <div v-else class="mt-5 p-4 bg-primary-50 border border-primary-200 rounded-lg">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3">
            <UAvatar :alt="customerDisplayName(selectedCustomer)" size="sm" />
            <div>
              <p class="font-medium text-primary-800">{{ customerDisplayName(selectedCustomer) }}</p>
              <p class="text-xs text-primary-600">{{ customerSubtitle(selectedCustomer) }}</p>
            </div>
          </div>
          <UButton size="sm" color="neutral" variant="ghost" @click="selectedCustomer = null">
            Change
          </UButton>
        </div>
      </div>

      <!-- Buyer Section -->
      <div class="mt-10 border-t border-[var(--sidebar-border)] pt-10">
        <div class="flex items-center gap-3 mb-4">
          <h3 class="text-base font-semibold text-[var(--text-primary)]">Buyer</h3>
          <div class="flex items-center gap-2">
            <UToggle v-model="useSameForBuyer" />
            <span class="text-sm text-[var(--text-muted)]">Same as insured</span>
          </div>
        </div>
        
        <p v-if="useSameForBuyer" class="mt-1 text-sm text-[var(--text-muted)]">
          Using same person as insured
        </p>
        
        <div v-else class="mt-5">
          <UInput
            v-model="customerSearch"
            icon="i-heroicons-magnifying-glass"
            placeholder="Search by name, email, RUC..."
            class="w-full max-w-sm mb-4"
          />
          
          <div v-if="customersPending" class="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div v-for="n in 3" :key="n" class="h-16 animate-pulse bg-gray-100 rounded-lg" />
          </div>
          
          <div v-else class="space-y-3 max-h-72 overflow-y-auto">
            <div
              v-for="c in customerItems"
              :key="c.id"
              class="flex items-center gap-3 p-3 border-2 rounded-lg cursor-pointer transition-all"
              :class="selectedBuyer?.id === c.id
                ? 'border-primary-500 bg-primary-50'
                : 'border-gray-200 hover:border-gray-300 bg-white'"
              @click="selectBuyer(c)"
            >
              <UAvatar :alt="customerDisplayName(c)" size="sm" />
              <div class="min-w-0 flex-1">
                <div class="flex items-center gap-1.5">
                  <p class="font-medium text-sm text-slate-800 truncate">{{ customerDisplayName(c) }}</p>
                  <UBadge
                    :color="c.customer_type === 'corporate' ? 'purple' : 'blue'"
                    variant="soft" size="xs" class="flex-shrink-0"
                  >
                    {{ c.customer_type === 'corporate' ? 'Corp' : 'Ind' }}
                  </UBadge>
                </div>
                <p class="text-xs text-gray-400 truncate">{{ customerSubtitle(c) }}</p>
              </div>
              <UIcon
                v-if="selectedBuyer?.id === c.id"
                name="i-heroicons-check-circle"
                class="w-5 h-5 text-primary-500 flex-shrink-0"
              />
            </div>
            
            <div v-if="customerItems.length === 0" class="text-center py-6 text-gray-400 text-sm">
              No customers found.
            </div>
          </div>
        </div>
      </div>

      <!-- Health Questionnaire -->
      <h3 class="mt-10 text-base font-semibold text-[var(--text-primary)]">Health Information</h3>
      <p class="mt-1 text-sm text-[var(--text-muted)]">Basic underwriting inputs — carriers use these to determine eligibility and rate class.</p>
      <div class="mt-5 space-y-4 rounded-xl border border-[var(--sidebar-border)] bg-[var(--surface)] p-4">
        <UCheckbox v-model="draft.life.smoker" label="Smoker / tobacco user (within last 12 months)" />
        
        <UFormField label="Medications">
          <UTextarea
            v-model="draft.life.medications"
            :class="inputPh"
            placeholder="List any current medications..."
            :rows="2"
          />
        </UFormField>
        
        <UFormField label="Surgeries">
          <UTextarea
            v-model="draft.life.surgeries"
            :class="inputPh"
            placeholder="List any past surgeries..."
            :rows="2"
          />
        </UFormField>
        
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <UFormField label="Weight (kg)">
            <UInput v-model="draft.life.weight" type="number" :class="inputPh" placeholder="—" />
          </UFormField>
          <UFormField label="Height (cm)">
            <UInput v-model="draft.life.height" type="number" :class="inputPh" placeholder="—" />
          </UFormField>
        </div>
      </div>

      <!-- Coverage parameters -->
      <h3 class="mt-10 text-base font-semibold text-[var(--text-primary)]">Coverage Details</h3>
      <p class="mt-1 text-sm text-[var(--text-muted)]">Sum assured, term, and coverage type.</p>
      <div class="mt-5 grid grid-cols-1 gap-4 md:grid-cols-3">
        <UFormField label="Coverage type" required>
          <USelect
            v-model="draft.life.coverage_type"
            :items="[
              { label: 'Banking', value: 'banking' },
              { label: 'Protection', value: 'protection' }
            ]"
            placeholder="Select one"
            class="w-full"
          />
        </UFormField>
        <UFormField label="Coverage amount (USD)" required>
          <USelect
            v-model="draft.life.coverage_amount"
            :items="LIFE_COVERAGE_AMOUNT_OPTIONS"
            value-key="value"
            label-key="label"
            placeholder="Select one"
            class="w-full"
          />
        </UFormField>
        <UFormField label="Coverage years" required>
          <USelect
            v-model="draft.life.coverage_years"
            :items="LIFE_COVERAGE_TERM_OPTIONS"
            value-key="value"
            label-key="label"
            placeholder="Select one"
            class="w-full"
          />
        </UFormField>
      </div>

      <!-- Forms -->
      <h3 class="mt-10 text-base font-semibold text-[var(--text-primary)]">Forms</h3>
      <p class="mt-1 text-sm text-[var(--text-muted)]">
        Confirm required templates are completed (uploads wire to the forms library later).
      </p>
      <div class="mt-4 space-y-3 rounded-xl border border-[var(--sidebar-border)] bg-[var(--surface)] p-4">
        <UCheckbox v-model="draft.forms.medicalQuestionnaire" label="Medical questionnaire (declaracion de salud)" />
        <UCheckbox v-model="draft.forms.beneficiaryDesignation" label="Beneficiary designation form" />
        <UCheckbox
          v-model="draft.forms.groupCensus"
          label="Group census / employee roster (required for group policies)"
          :disabled="draft.segment !== 'group'"
        />
      </div>
    </section>
    <div
      v-else
      class="mt-10 min-h-[8rem] rounded-xl bg-[var(--sidebar-border)]/25 animate-pulse"
      aria-busy="true"
      aria-label="Loading"
    />
  </div>
</template>
