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

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

// ---------------------------------------------------------------------------
// Buyer and Insured Information
// ---------------------------------------------------------------------------

const buyerInfo = ref({
  type: 'individual' as 'individual' | 'corporate',
  name: '',
  date_of_birth: '',
  document_id: '',
  email: '',
  phone: '',
  address: '',
  company_name: '',
  ruc: '',
  legal_rep_name: '',
  legal_rep_document: ''
})

const insuredInfo = ref({
  type: 'individual' as 'individual' | 'corporate',
  name: '',
  date_of_birth: '',
  document_id: '',
  gender: 'male' as 'male' | 'female',
  email: '',
  phone: '',
  address: '',
  company_name: '',
  ruc: '',
  legal_rep_name: '',
  legal_rep_document: ''
})

function copyBuyerToInsured() {
  insuredInfo.value = { ...buyerInfo.value }
}

const isBuyerValid = computed(() => {
  const b = buyerInfo.value
  if (b.type === 'corporate') {
    return !!(b.company_name && b.ruc && b.legal_rep_name && b.legal_rep_document)
  }
  return !!(b.name && b.date_of_birth && b.document_id)
})

const isInsuredValid = computed(() => {
  const i = insuredInfo.value
  if (i.type === 'corporate') {
    return !!(i.company_name && i.ruc && i.legal_rep_name && i.legal_rep_document)
  }
  return !!(i.name && i.date_of_birth && i.document_id && i.gender)
})

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

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

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

const carForm = ref({
  car_details: {
    plate:          '',
    make:           '',
    model:          '',
    year:           new Date().getFullYear(),
    market_value:   '',
    requested_value: '',
    use_type:       'private',
    car_type:       'sedan',
    chassis_number: '',
    engine_number:  '',
    rc_limits: {
      bodily_injury: 0,
      property_damage: 0
    }
  },
  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',
        buyer:              buyerInfo.value,
        insured:            insuredInfo.value,
        insured_object:     carForm.value.car_details,
        selected_providers: carForm.value.selected_providers
      }
    }) as any

    toast.add({ title: 'Policy submitted successfully', color: 'green' })
    router.push(`/policies/${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 (
    isBuyerValid.value &&
    isInsuredValid.value &&
    car_details.plate &&
    car_details.make &&
    car_details.model &&
    car_details.year &&
    car_details.market_value &&
    car_details.requested_value &&
    car_details.rc_limits &&
    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>

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

      <div class="space-y-4">
        <div class="flex gap-4 mb-4">
          <UFormField label="Type" required class="flex-1">
            <USelect v-model="buyerInfo.type" :items="[{label: 'Individual', value: 'individual'}, {label: 'Corporate', value: 'corporate'}]" class="w-full" />
          </UFormField>
        </div>

        <template v-if="buyerInfo.type === 'individual'">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Full Name" required class="col-span-2">
              <UInput v-model="buyerInfo.name" placeholder="Juan Pérez" class="w-full" />
            </UFormField>
            <UFormField label="Date of Birth" required>
              <UInput v-model="buyerInfo.date_of_birth" type="date" class="w-full" />
            </UFormField>
            <UFormField label="Document ID" required>
              <UInput v-model="buyerInfo.document_id" placeholder="8-123-456" class="w-full" />
            </UFormField>
            <UFormField label="Email">
              <UInput v-model="buyerInfo.email" type="email" placeholder="juan@example.com" class="w-full" />
            </UFormField>
            <UFormField label="Phone">
              <UInput v-model="buyerInfo.phone" placeholder="+507-1234-5678" class="w-full" />
            </UFormField>
            <UFormField label="Address" class="col-span-2">
              <UInput v-model="buyerInfo.address" placeholder="Calle 50, Panama City" class="w-full" />
            </UFormField>
          </div>
        </template>

        <template v-else>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Company Name" required class="col-span-2">
              <UInput v-model="buyerInfo.company_name" placeholder="Empresa XYZ S.A." class="w-full" />
            </UFormField>
            <UFormField label="RUC" required>
              <UInput v-model="buyerInfo.ruc" placeholder="987654-1-987654" class="w-full" />
            </UFormField>
            <UFormField label="Legal Representative Name" required>
              <UInput v-model="buyerInfo.legal_rep_name" placeholder="Carlos López" class="w-full" />
            </UFormField>
            <UFormField label="Legal Representative Document" required>
              <UInput v-model="buyerInfo.legal_rep_document" placeholder="8-789-012" class="w-full" />
            </UFormField>
            <UFormField label="Email">
              <UInput v-model="buyerInfo.email" type="email" placeholder="carlos@empresa-xyz.com" class="w-full" />
            </UFormField>
            <UFormField label="Phone">
              <UInput v-model="buyerInfo.phone" placeholder="+507-8765-4321" class="w-full" />
            </UFormField>
            <UFormField label="Address" class="col-span-2">
              <UInput v-model="buyerInfo.address" placeholder="Calle 100, Panama City" class="w-full" />
            </UFormField>
          </div>
        </template>
      </div>
    </UCard>

    <!-- Insured Information -->
    <UCard>
      <template #header>
        <div class="flex justify-between items-center">
          <p class="font-semibold text-[var(--text-primary)] flex items-center gap-2">
            <UIcon name="i-heroicons-shield-check" class="w-4 h-4" />
            Insured Information
          </p>
          <UButton size="xs" color="gray" variant="soft" @click="copyBuyerToInsured">
            Copy from Buyer
          </UButton>
        </div>
      </template>

      <div class="space-y-4">
        <div class="flex gap-4 mb-4">
          <UFormField label="Type" required class="flex-1">
            <USelect v-model="insuredInfo.type" :items="[{label: 'Individual', value: 'individual'}, {label: 'Corporate', value: 'corporate'}]" class="w-full" />
          </UFormField>
        </div>

        <template v-if="insuredInfo.type === 'individual'">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Full Name" required class="col-span-2">
              <UInput v-model="insuredInfo.name" placeholder="María García" class="w-full" />
            </UFormField>
            <UFormField label="Date of Birth" required>
              <UInput v-model="insuredInfo.date_of_birth" type="date" class="w-full" />
            </UFormField>
            <UFormField label="Document ID" required>
              <UInput v-model="insuredInfo.document_id" placeholder="8-456-789" class="w-full" />
            </UFormField>
            <UFormField label="Gender" required>
              <USelect v-model="insuredInfo.gender" :items="[{label: 'Male', value: 'male'}, {label: 'Female', value: 'female'}]" class="w-full" />
            </UFormField>
            <UFormField label="Email">
              <UInput v-model="insuredInfo.email" type="email" placeholder="maria@example.com" class="w-full" />
            </UFormField>
            <UFormField label="Phone">
              <UInput v-model="insuredInfo.phone" placeholder="+507-8765-4321" class="w-full" />
            </UFormField>
            <UFormField label="Address" class="col-span-2">
              <UInput v-model="insuredInfo.address" placeholder="Calle 75, Panama City" class="w-full" />
            </UFormField>
          </div>
        </template>

        <template v-else>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Company Name" required class="col-span-2">
              <UInput v-model="insuredInfo.company_name" placeholder="Empresa ABC S.A." class="w-full" />
            </UFormField>
            <UFormField label="RUC" required>
              <UInput v-model="insuredInfo.ruc" placeholder="123456-1-123456" class="w-full" />
            </UFormField>
            <UFormField label="Legal Representative Name" required>
              <UInput v-model="insuredInfo.legal_rep_name" placeholder="María García" class="w-full" />
            </UFormField>
            <UFormField label="Legal Representative Document" required>
              <UInput v-model="insuredInfo.legal_rep_document" placeholder="8-456-789" class="w-full" />
            </UFormField>
            <UFormField label="Email">
              <UInput v-model="insuredInfo.email" type="email" placeholder="contact@empresa-abc.com" class="w-full" />
            </UFormField>
            <UFormField label="Phone">
              <UInput v-model="insuredInfo.phone" placeholder="+507-1234-5678" class="w-full" />
            </UFormField>
            <UFormField label="Address" class="col-span-2">
              <UInput v-model="insuredInfo.address" placeholder="Calle 50, Panama City" class="w-full" />
            </UFormField>
          </div>
        </template>
      </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="Market Value (USD)" required>
            <UInput v-model="carForm.car_details.market_value" type="number" placeholder="18000" class="w-full" />
          </UFormField>
          <UFormField label="Requested Value (USD)" required>
            <UInput v-model="carForm.car_details.requested_value" type="number" placeholder="20000" 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">
            <UInput v-model="carForm.car_details.chassis_number" placeholder="9BWZZZ377VT004251" class="w-full" />
          </UFormField>
          <UFormField label="Engine Number">
            <UInput v-model="carForm.car_details.engine_number" placeholder="1NZ-FE-1234567" class="w-full" />
          </UFormField>
        </div>

        <!-- RC Limits -->
        <div class="mt-6 pt-6 border-t">
          <p class="font-medium text-sm text-[var(--text-primary)] mb-4">RC Limits</p>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Bodily Injury Limit (USD)" required>
              <UInput v-model.number="carForm.car_details.rc_limits.bodily_injury" type="number" placeholder="50000" class="w-full" />
            </UFormField>
            <UFormField label="Property Damage Limit (USD)" required>
              <UInput v-model.number="carForm.car_details.rc_limits.property_damage" type="number" placeholder="25000" class="w-full" />
            </UFormField>
          </div>
        </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>

<style scoped>
/* Prevent width expansion when dropdowns open */
:deep(.grid) {
  min-width: 0;
  width: 100%;
}

:deep(.UFormField) {
  min-width: 0;
  width: 100%;
}

:deep(.UInput) {
  min-width: 0;
  width: 100%;
}

:deep(.USelect) {
  min-width: 0;
  width: 100%;
}

/* Prevent dropdown menus from expanding container */
:deep([role="listbox"]) {
  position: fixed !important;
  z-index: 50;
  min-width: 200px;
  max-width: 300px;
}

/* Ensure form fields don't cause expansion */
:deep(.space-y-4) {
  min-width: 0;
  width: 100%;
  overflow: hidden;
}

/* Prevent any element from expanding beyond container */
:deep(*) {
  max-width: 100%;
}

/* Specific fix for dropdown positioning */
:deep(.USelectMenuPopover) {
  position: fixed !important;
  z-index: 100;
}

/* Ensure form stability */
:deep(.UCard) {
  width: 100%;
  min-width: 0;
}
</style>
