<script setup lang="ts">
import type { SelectItem } from '@nuxt/ui'
import { refDebounced } from '@vueuse/core'

const router = useRouter()
const policyType = ref<'car' | 'life' | 'fire'>('car')
const submitting  = ref(false)
const toast       = useToast()
const { $policy } = useNuxtApp()

// ---------------------------------------------------------------------------
// Customer selection
// ---------------------------------------------------------------------------

const customerSearch          = ref('')
const debouncedCustomerSearch = refDebounced(customerSearch, 300)
const customerPage            = ref(1)
const selectedCustomer        = ref<any>(null)

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 ?? [])
const customerMeta  = computed(() => customersData.value?.meta)

function selectCustomer(customer: any) {
  selectedCustomer.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

// Build applicant_info from selected customer — shape varies by type
const applicantInfo = computed(() => {
  const c = selectedCustomer.value
  if (!c) return null
  if (c.customer_type === 'corporate') {
    return {
      company_name:       c.legal_name,
      ruc:                c.ruc,
      legal_rep_name:     c.legal_rep_name,
      legal_rep_document: c.legal_rep_document_id
    }
  }
  return {
    name:          `${c.first_name} ${c.last_name}`.trim(),
    date_of_birth: c.birth_date,
    document_id:   c.document_id
  }
})

const isApplicantValid = computed(() => {
  const c = selectedCustomer.value
  if (!c) return false
  if (c.customer_type === 'corporate') {
    return !!(c.legal_name && c.ruc)
  }
  return !!(c.birth_date && c.document_id)
})

// ---------------------------------------------------------------------------
// Policy type
// ---------------------------------------------------------------------------

const policyTypeItems = ref<SelectItem[]>([
  { label: 'Car Insurance',  value: 'car'  },
  { label: 'Life Insurance', value: 'life', disabled: true },
  { label: 'Fire Insurance', value: 'fire', disabled: true }
])

// ---------------------------------------------------------------------------
// Car form
// ---------------------------------------------------------------------------

const carForm = ref({
  car_details: {
    plate:          '',
    make:           '',
    model:          '',
    year:           new Date().getFullYear(),
    car_value:      '',
    use_type:       'private',
    car_type:       'sedan',
    chassis_number: '',
    engine_number:  ''
  },
  selected_providers: [] as { provider_id: string, email: string }[]
})

const useTypeItems = ref<SelectItem[]>([
  { label: 'Private',    value: 'private'    },
  { label: 'Commercial', value: 'commercial' },
  { label: 'Bus',        value: 'bus'        },
  { label: 'Taxi',       value: 'taxi'       },
  { label: 'School',     value: 'school'     }
])

const carTypeItems = ref<SelectItem[]>([
  { label: 'Sedan',       value: 'sedan'       },
  { label: 'SUV',         value: 'suv'         },
  { label: 'Hatchback',   value: 'hatchback'   },
  { label: 'Coupe',       value: 'coupe'       },
  { label: 'Convertible', value: 'convertible' },
  { label: 'Pickup',      value: 'pickup'      },
  { label: 'Van',         value: 'van'         },
  { label: 'Minivan',     value: 'minivan'     },
  { label: 'Truck',       value: 'truck'       }
])

// ---------------------------------------------------------------------------
// Provider selection
// ---------------------------------------------------------------------------

const providerSearch          = ref('')
const debouncedProviderSearch = refDebounced(providerSearch, 300)

const { data: providersData, pending: providersPending } = useProviders('/providers', {
  query: computed(() => ({
    ...(debouncedProviderSearch.value && {
      'filters[0][field]': 'search',
      'filters[0][op]':    '==',
      'filters[0][value]': debouncedProviderSearch.value
    })
  }))
})

const providerItems = computed(() => providersData.value?.data ?? [])

function toggleProvider(provider: any) {
  const idx = carForm.value.selected_providers.findIndex(p => p.provider_id === provider.provider_id)
  if (idx >= 0) {
    carForm.value.selected_providers.splice(idx, 1)
  } else {
    carForm.value.selected_providers.push({
      provider_id: provider.provider_id,
      email:       provider.email
    })
  }
}

function isProviderSelected(provider: any) {
  return carForm.value.selected_providers.some(p => p.provider_id === provider.provider_id)
}

// ---------------------------------------------------------------------------
// Submit
// ---------------------------------------------------------------------------

async function submitCarPolicy() {
  submitting.value = true
  try {
    const data = await $policy('/policies', {
      method: 'POST',
      body: {
        policy_type:        'car',
        applicant_info:     applicantInfo.value,
        policy_details:     carForm.value.car_details,
        selected_providers: carForm.value.selected_providers
      }
    }) as any

    toast.add({ title: 'Policy submitted successfully', color: 'green' })
    router.push(`/policies/app/${data.application_id}`)
  } catch (e: any) {
    toast.add({
      title:       'Failed to submit policy',
      description: e?.data?.error ? JSON.stringify(e.data.error) : e.message,
      color:       'red'
    })
  } finally {
    submitting.value = false
  }
}

const isCarFormValid = computed(() => {
  const { car_details, selected_providers } = carForm.value
  return (
    isApplicantValid.value &&
    car_details.plate &&
    car_details.make &&
    car_details.model &&
    car_details.year &&
    car_details.car_value &&
    car_details.chassis_number &&
    car_details.engine_number &&
    selected_providers.length > 0
  )
})
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <!-- Header -->
    <div class="flex items-center gap-4">
      <NuxtLink to="/policies">
        <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">
          Back to Policies
        </UButton>
      </NuxtLink>
      <div>
        <h1 class="text-2xl font-semibold tracking-tight text-[var(--text-primary)]">New Policy</h1>
        <p class="text-[13px] text-[var(--text-muted)]">Submit a new insurance policy quote request</p>
      </div>
    </div>

    <!-- Customer Selection -->
    <UCard>
      <template #header>
        <p class="font-semibold text-[var(--text-primary)] flex items-center gap-2">
          <UIcon name="i-heroicons-users" class="w-4 h-4" />
          Select Customer
        </p>
      </template>

      <div class="space-y-4">
        <UInput
          v-model="customerSearch"
          icon="i-heroicons-magnifying-glass"
          placeholder="Search by name, email, RUC..."
          class="w-full max-w-sm"
        />

        <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">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-h-72 overflow-y-auto pr-1">
            <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-[var(--surface)]'"
              @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-[var(--text-primary)] 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="col-span-3 text-center py-6 text-gray-400 text-sm">
              No customers found.
              <NuxtLink to="/customers/new" class="text-primary-500 underline ml-1">Create one</NuxtLink>
            </div>
          </div>

          <div v-if="customerMeta && customerMeta.total_pages > 1" class="flex justify-between items-center text-sm text-gray-500">
            <span>{{ customerMeta.total_count }} customers</span>
            <UPagination
              v-model="customerPage"
              :total="customerMeta.total_count"
              :page-count="customerMeta.page_size"
              size="sm"
            />
          </div>
        </div>

        <!-- Selected summary -->
        <div
          v-if="selectedCustomer"
          class="flex items-center gap-4 p-3 bg-primary-50 border border-primary-200 rounded-lg text-sm"
        >
          <UAvatar :alt="customerDisplayName(selectedCustomer)" size="sm" />
          <div class="flex-1">
            <div class="flex items-center gap-2">
              <p class="font-medium text-primary-800">{{ customerDisplayName(selectedCustomer) }}</p>
              <UBadge
                :color="selectedCustomer.customer_type === 'corporate' ? 'purple' : 'blue'"
                variant="soft" size="xs"
              >
                {{ selectedCustomer.customer_type === 'corporate' ? 'Corporate' : 'Individual' }}
              </UBadge>
            </div>
            <p class="text-primary-600 text-xs">{{ selectedCustomer.email }}</p>
          </div>
          <div class="text-xs text-primary-600 text-right space-y-0.5">
            <template v-if="selectedCustomer.customer_type === 'corporate'">
              <p>RUC: {{ selectedCustomer.ruc ?? '—' }}</p>
              <p>Rep: {{ selectedCustomer.legal_rep_name ?? '—' }}</p>
            </template>
            <template v-else>
              <p>DOB: {{ selectedCustomer.birth_date ?? '—' }}</p>
              <p>Doc: {{ selectedCustomer.document_id ?? '—' }}</p>
            </template>
          </div>
          <UButton size="xs" color="gray" variant="ghost" @click="selectedCustomer = null">Change</UButton>
        </div>

        <!-- Warn if individual customer missing required fields -->
        <UAlert
          v-if="selectedCustomer && selectedCustomer.customer_type !== 'corporate' && (!selectedCustomer.birth_date || !selectedCustomer.document_id)"
          color="yellow" variant="soft" icon="i-heroicons-exclamation-triangle"
          title="Incomplete customer record"
          description="This customer is missing date of birth or document ID. Please update their record before submitting."
        />
      </div>
    </UCard>

    <!-- Policy Type -->
    <UCard>
      <template #header>
        <p class="font-semibold text-[var(--text-primary)]">Policy Type</p>
      </template>
      <div class="flex gap-4">
        <div
          v-for="item in policyTypeItems"
          :key="item.value"
          class="flex-1 border-2 rounded-xl p-4 text-center transition-all"
          :class="[
            item.disabled
              ? 'border-gray-100 bg-gray-50 opacity-40 cursor-not-allowed'
              : policyType === item.value
                ? 'border-primary-500 bg-primary-50 cursor-pointer'
                : 'border-gray-200 bg-[var(--surface)] hover:border-gray-300 cursor-pointer'
          ]"
          @click="!item.disabled && (policyType = item.value as any)"
        >
          <UIcon
            :name="item.value === 'car' ? 'i-heroicons-truck' : item.value === 'life' ? 'i-heroicons-heart' : 'i-heroicons-home'"
            class="w-8 h-8 mx-auto mb-2"
            :class="policyType === item.value ? 'text-primary-500' : 'text-gray-400'"
          />
          <p class="font-medium text-sm" :class="policyType === item.value ? 'text-primary-700' : 'text-gray-600'">
            {{ item.label }}
          </p>
          <p v-if="item.disabled" class="text-xs text-gray-400 mt-1">Coming soon</p>
        </div>
      </div>
    </UCard>

    <!-- Car Form -->
    <template v-if="policyType === 'car'">
      <UCard>
        <template #header>
          <p class="font-semibold text-[var(--text-primary)] flex items-center gap-2">
            <UIcon name="i-heroicons-truck" class="w-4 h-4" />
            Vehicle Details
          </p>
        </template>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <UFormField label="Plate" required>
            <UInput v-model="carForm.car_details.plate" placeholder="ABC-1234" class="w-full" />
          </UFormField>
          <UFormField label="Make" required>
            <UInput v-model="carForm.car_details.make" placeholder="Toyota" class="w-full" />
          </UFormField>
          <UFormField label="Model" required>
            <UInput v-model="carForm.car_details.model" placeholder="Corolla" class="w-full" />
          </UFormField>
          <UFormField label="Year" required>
            <UInput
              v-model.number="carForm.car_details.year"
              type="number"
              :min="1886"
              :max="new Date().getFullYear() + 1"
              class="w-full"
            />
          </UFormField>
          <UFormField label="Car Value (USD)" required>
            <UInput v-model="carForm.car_details.car_value" type="number" placeholder="18000" class="w-full" />
          </UFormField>
          <UFormField label="Use Type" required>
            <USelect v-model="carForm.car_details.use_type" :items="useTypeItems" class="w-full" />
          </UFormField>
          <UFormField label="Car Type" required>
            <USelect v-model="carForm.car_details.car_type" :items="carTypeItems" class="w-full" />
          </UFormField>
          <UFormField label="Chassis Number" required>
            <UInput v-model="carForm.car_details.chassis_number" placeholder="9BWZZZ377VT004251" class="w-full" />
          </UFormField>
          <UFormField label="Engine Number" required>
            <UInput v-model="carForm.car_details.engine_number" placeholder="1NZ-FE-1234567" class="w-full" />
          </UFormField>
        </div>
      </UCard>

      <!-- Provider Selection -->
      <UCard>
        <template #header>
          <p class="font-semibold text-[var(--text-primary)] flex items-center gap-2">
            <UIcon name="i-heroicons-building-office" class="w-4 h-4" />
            Selected Providers
            <UBadge color="gray" variant="soft" size="xs">
              {{ carForm.selected_providers.length }} selected
            </UBadge>
          </p>
        </template>

        <div class="space-y-4">
          <UInput
            v-model="providerSearch"
            icon="i-heroicons-magnifying-glass"
            placeholder="Search providers..."
            class="w-full max-w-sm"
          />

          <div v-if="providersPending" 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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-h-72 overflow-y-auto pr-1">
            <div
              v-for="p in providerItems"
              :key="p.provider_id"
              class="flex items-center gap-3 p-3 border-2 rounded-lg cursor-pointer transition-all"
              :class="isProviderSelected(p)
                ? 'border-primary-500 bg-primary-50'
                : 'border-gray-200 hover:border-gray-300 bg-[var(--surface)]'"
              @click="toggleProvider(p)"
            >
              <div class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0">
                <UIcon name="i-heroicons-building-office" class="w-4 h-4 text-gray-500" />
              </div>
              <div class="min-w-0 flex-1">
                <p class="font-medium text-sm text-[var(--text-primary)] truncate">{{ p.name }}</p>
                <p class="text-xs text-gray-400 truncate">{{ p.email }}</p>
              </div>
              <UIcon
                v-if="isProviderSelected(p)"
                name="i-heroicons-check-circle"
                class="w-5 h-5 text-primary-500 flex-shrink-0"
              />
            </div>

            <div v-if="providerItems.length === 0" class="col-span-3 text-center py-6 text-gray-400 text-sm">
              No providers found.
              <NuxtLink to="/providers/new" class="text-primary-500 underline ml-1">Create one</NuxtLink>
            </div>
          </div>

          <div v-if="carForm.selected_providers.length > 0" class="flex flex-wrap gap-2 pt-2 border-t">
            <div
              v-for="p in carForm.selected_providers"
              :key="p.provider_id"
              class="flex items-center gap-1.5 px-3 py-1 bg-primary-50 border border-primary-200 rounded-full text-sm"
            >
              <UIcon name="i-heroicons-building-office" class="w-3.5 h-3.5 text-primary-500" />
              <span class="text-primary-800 font-medium">
                {{ providerItems.find(x => x.provider_id === p.provider_id)?.name ?? p.provider_id }}
              </span>
              <UButton
                icon="i-heroicons-x-mark"
                size="xs" color="gray" variant="ghost"
                class="w-4 h-4 p-0"
                @click="carForm.selected_providers = carForm.selected_providers.filter(x => x.provider_id !== p.provider_id)"
              />
            </div>
          </div>
        </div>
      </UCard>

      <!-- Submit -->
      <div class="flex justify-end gap-3">
        <NuxtLink to="/policies">
          <UButton color="gray" variant="soft">Cancel</UButton>
        </NuxtLink>
        <UButton
          color="primary"
          icon="i-heroicons-paper-airplane"
          :loading="submitting"
          :disabled="!isCarFormValid"
          @click="submitCarPolicy"
        >
          Submit Quote Request
        </UButton>
      </div>
    </template>
  </div>
</template>
