<script setup lang="ts">
definePageMeta({ ssr: false })

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

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

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

usePageTitle(computed(() => {
  if (!customer.value) return 'Customer'
  if (isIndividual.value) {
    const full = [customer.value.first_name, customer.value.last_name].filter(Boolean).join(' ')
    return full || 'Unnamed customer'
  }
  return customer.value.commercial_name || customer.value.legal_name || 'Unnamed company'
}))

const activeTab = ref<'details' | 'policies'>('details')

function customerName() {
  if (!customer.value) return 'Unnamed customer'
  if (isIndividual.value) {
    const full = [customer.value.first_name, customer.value.last_name].filter(Boolean).join(' ')
    return full || 'Unnamed customer'
  }
  return customer.value.commercial_name || customer.value.legal_name || 'Unnamed company'
}

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

const { data: policiesData } = usePolicy('/policies', {
  query: computed(() => {
    if (!customer.value) return {}
    const filterValue = isIndividual.value ? customer.value.document_id : customer.value.ruc
    if (!filterValue) return {}
    return {
      'filters[0][field]': 'search',
      'filters[0][op]': '==',
      'filters[0][value]': filterValue
    }
  })
})

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

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

    <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>

    <template v-else-if="customer">
      <div class="cp-header">
        <div class="cp-header-left">
          <div class="cp-avatar">
            {{ isIndividual ? customer.first_name?.[0] : customer.commercial_name?.[0] || customer.legal_name?.[0] || '?' }}
          </div>
          <div class="cp-header-info">
            <div class="cp-header-name-row">
              <h1 class="cp-name">{{ customerName() }}</h1>
              <span class="cp-type-badge">{{ customer.customer_type === 'corporate' ? 'Corporate' : 'Individual' }}</span>
            </div>
            <div class="cp-header-meta">
              <span>{{ isIndividual ? customer.document_id : customer.ruc }}</span>
              <span class="cp-sep" />
              <span>{{ customer.email || '—' }}</span>
              <span class="cp-sep" />
              <span>{{ customer.phone }}</span>
            </div>
          </div>
        </div>
        <div class="cp-header-actions">
          <UButton size="sm" color="neutral" variant="outline" icon="i-heroicons-pencil-square">Edit</UButton>
          <UButton size="sm" color="primary" icon="i-heroicons-document-text">New Quote</UButton>
        </div>
      </div>

      <div class="cp-main-grid">
        <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>Personal Details</span>
          </div>
          <div class="cp-detail-list">
            <div v-if="isIndividual">
              <div class="cp-detail-row">
                <span class="cp-detail-label">Full Name</span>
                <span class="cp-detail-value">{{ customer.first_name }} {{ customer.last_name }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Document ID</span>
                <span class="cp-detail-value cp-mono">{{ customer.document_id }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Email</span>
                <span class="cp-detail-value">{{ customer.email || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Phone</span>
                <span class="cp-detail-value">{{ customer.phone }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Date of Birth</span>
                <span class="cp-detail-value">{{ formatDate(customer.birth_date) }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Gender</span>
                <span class="cp-detail-value">{{ customer.gender || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Address</span>
                <span class="cp-detail-value">{{ customer.address || '—' }}</span>
              </div>
            </div>
            <div v-else>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Commercial Name</span>
                <span class="cp-detail-value">{{ customer.commercial_name || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Legal Name</span>
                <span class="cp-detail-value">{{ customer.legal_name || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">RUC</span>
                <span class="cp-detail-value cp-mono">{{ customer.ruc }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Email</span>
                <span class="cp-detail-value">{{ customer.email || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Phone</span>
                <span class="cp-detail-value">{{ customer.phone }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Legal Rep Name</span>
                <span class="cp-detail-value">{{ customer.legal_rep_name || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Legal Rep Document</span>
                <span class="cp-detail-value cp-mono">{{ customer.legal_rep_document_id || '—' }}</span>
              </div>
              <div class="cp-detail-row">
                <span class="cp-detail-label">Address</span>
                <span class="cp-detail-value">{{ customer.address || '—' }}</span>
              </div>
            </div>
          </div>
        </div>

        <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 === 'policies' ? 'cp-tab-on' : 'cp-tab-off'"
              @click="activeTab = 'policies'"
            >
              Policies
              <span class="cp-tab-count" :class="activeTab === 'policies' ? 'cp-tab-count-on' : ''">{{ customerPolicies.length }}</span>
            </button>
          </div>

          <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>Customer Information</span>
              </div>
              <div class="p-4 text-sm text-gray-600">
                <p>This customer has {{ customerPolicies.length }} policy{{ customerPolicies.length !== 1 ? 'ies' : '' }} on file.</p>
              </div>
            </div>
          </div>

          <div v-if="activeTab === 'policies'" class="cp-tab-content">
            <div v-if="customerPolicies.length > 0" class="cp-card">
              <div v-for="policy in customerPolicies" :key="policy.id" class="cp-row" style="cursor: pointer;" @click="navigateTo(`/policies/${policy.id}`)">
                <div class="cp-row-main">
                  <div class="cp-row-top">
                    <p class="cp-row-title">{{ policy.policy_type }}</p>
                    <span class="cp-status cp-status-ok">{{ policy.status }}</span>
                  </div>
                  <p class="cp-row-sub">Policy {{ policy.application_id }}</p>
                </div>
              </div>
            </div>
            <p v-else class="cp-empty-msg">No policies on file</p>
          </div>
        </div>
      </div>
    </template>

    <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">Customer not found</p>
        <NuxtLink to="/customers">
          <UButton color="neutral" variant="ghost" class="mt-4">Back to Customers</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-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(15, 123, 95, 0.08);
  color: #0f7b5f;
}

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