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

const { data, error, pending, refresh } = useCustomer(`/customers/${id}`)
const customer = computed(() => data.value?.data)

const isIndividual = computed(() => customer.value?.customer_type !== 'corporate')

const customerName = computed(() => {
  if (!customer.value) return ''
  return isIndividual.value
    ? `${customer.value.first_name} ${customer.value.last_name}`
    : (customer.value.commercial_name || customer.value.legal_name)
})

// policies — individual uses document_id, corporate uses ruc
const policyFilterValue = computed(() =>
  isIndividual.value ? customer.value?.document_id : customer.value?.ruc
)
const policyFilterField = computed(() =>
  isIndividual.value ? 'applicant_document' : 'applicant_document'
)

const { data: policiesData } = usePolicy('/car-policies', {
  query: computed(() => policyFilterValue.value ? {
    'filters[0][field]': policyFilterField.value,
    'filters[0][op]':    '==',
    'filters[0][value]': policyFilterValue.value
  } : {})
})

const customerPolicies = computed(() => policiesData.value?.data ?? [])

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

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

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

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

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

    <template v-else-if="customer">
      <!-- Header -->
      <div class="flex justify-between items-start">
        <div class="flex items-center gap-4">
          <UAvatar :alt="customerName" size="xl" />
          <div>
            <div class="flex items-center gap-2 mb-1">
              <h1 class="text-2xl font-bold text-slate-900">{{ customerName }}</h1>
              <UBadge :color="isIndividual ? 'blue' : 'purple'" variant="soft" size="sm">
                {{ isIndividual ? 'Individual' : 'Corporate' }}
              </UBadge>
            </div>
            <p class="text-gray-500">{{ customer.email }}</p>
          </div>
        </div>
        <div class="flex gap-2">
          <UButton icon="i-heroicons-arrow-path" color="gray" variant="soft" :loading="pending" @click="refresh()" />
          <NuxtLink to="/policies/new">
            <UButton icon="i-heroicons-plus" color="primary" size="sm">New Policy</UButton>
          </NuxtLink>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        <!-- Individual details -->
        <UCard v-if="isIndividual" class="lg:col-span-1">
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-user" class="w-4 h-4" /> Customer Details
            </p>
          </template>
          <div class="space-y-3 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-500">ID</span>
              <span class="font-mono text-xs">{{ customer.id?.slice(0, 8) }}...</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Email</span>
              <span>{{ customer.email ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Phone</span>
              <span>{{ customer.phone ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Document ID</span>
              <span class="font-mono">{{ customer.document_id ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Birth Date</span>
              <span>{{ formatDate(customer.birth_date) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Gender</span>
              <span class="capitalize">{{ customer.gender ?? '—' }}</span>
            </div>
          </div>
        </UCard>

        <!-- Corporate details -->
        <UCard v-else class="lg:col-span-1">
          <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" /> Company Details
            </p>
          </template>
          <div class="space-y-3 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-500">ID</span>
              <span class="font-mono text-xs">{{ customer.id?.slice(0, 8) }}...</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Legal Name</span>
              <span class="text-right max-w-44 truncate">{{ customer.legal_name ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Commercial Name</span>
              <span>{{ customer.commercial_name ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">RUC</span>
              <span class="font-mono">{{ customer.ruc ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Legal Rep</span>
              <span>{{ customer.legal_rep_name ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Rep Document</span>
              <span class="font-mono">{{ customer.legal_rep_document_id ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Email</span>
              <span>{{ customer.email ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Phone</span>
              <span>{{ customer.phone ?? '—' }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-500">Address</span>
              <span class="text-right max-w-44 truncate">{{ customer.address ?? '—' }}</span>
            </div>
          </div>
        </UCard>

        <!-- Policies -->
        <UCard class="lg:col-span-2">
          <template #header>
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-document-text" class="w-4 h-4" />
              Policies
              <UBadge color="gray" variant="soft" size="xs">{{ customerPolicies.length }}</UBadge>
            </p>
          </template>

          <div class="space-y-3">
            <NuxtLink
              v-for="policy in customerPolicies"
              :key="policy.application_id"
              :to="`/policies/${policy.application_id}`"
            >
              <div class="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50 transition-colors cursor-pointer">
                <div class="flex items-center gap-3">
                  <UIcon name="i-heroicons-truck" class="w-5 h-5 text-blue-400" />
                  <div>
                    <p class="font-medium text-sm text-slate-800">
                      {{ policy.plate }} — {{ policy.year }} {{ policy.make }} {{ policy.model }}
                    </p>
                    <p class="text-xs text-gray-400 font-mono">{{ policy.application_id?.slice(0, 8) }}...</p>
                  </div>
                </div>
                <div class="flex items-center gap-2">
                  <UBadge :color="statusColor(policy.status)" variant="soft" size="xs">
                    {{ policy.status?.replace(/_/g, ' ') }}
                  </UBadge>
                  <UIcon name="i-heroicons-chevron-right" class="w-4 h-4 text-gray-400" />
                </div>
              </div>
            </NuxtLink>

            <div v-if="customerPolicies.length === 0" class="text-center py-8 text-gray-400">
              <UIcon name="i-heroicons-document-text" class="w-8 h-8 mx-auto mb-2" />
              <p class="text-sm">No policies yet</p>
            </div>
          </div>
        </UCard>
      </div>
    </template>
  </div>
</template>
