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

const router = useRouter()
const submitting = ref(false)
const toast = useToast()
const { $customer } = useNuxtApp()

const customerType = ref<'individual' | 'corporate'>('individual')

const individualForm = ref({
  first_name: '',
  last_name: '',
  email: '',
  phone: '',
  document_id: '',
  birth_date: '',
  address: ''
})

const corporateForm = ref({
  legal_name: '',
  commercial_name: '',
  email: '',
  phone: '',
  ruc: '',
  legal_rep_name: '',
  legal_rep_document_id: '',
  address: ''
})

const isValid = computed(() => {
  if (customerType.value === 'individual') {
    return !!(
      individualForm.value.first_name &&
      individualForm.value.last_name &&
      individualForm.value.email &&
      individualForm.value.document_id &&
      individualForm.value.birth_date
    )
  } else {
    return !!(
      corporateForm.value.legal_name &&
      corporateForm.value.email &&
      corporateForm.value.ruc &&
      corporateForm.value.legal_rep_name &&
      corporateForm.value.legal_rep_document_id
    )
  }
})

async function submit() {
  submitting.value = true
  try {
    const body = customerType.value === 'individual'
      ? {
          customer_type: 'individual',
          ...individualForm.value
        }
      : {
          customer_type: 'corporate',
          ...corporateForm.value
        }

    const data = await $customer('/customers', { method: 'POST', body }) as any
    toast.add({ title: 'Customer created successfully', color: 'green' })
    router.push(`/customers/${data.id}`)
  } catch (e: any) {
    toast.add({
      title: 'Failed to create customer',
      description: e?.data?.error ?? e.message,
      color: 'red'
    })
  } finally {
    submitting.value = false
  }
}
</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="/customers">
        <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">Back to Customers</UButton>
      </NuxtLink>
      <div>
        <h1 class="text-2xl font-semibold tracking-tight text-[var(--text-primary)]">New Customer</h1>
        <p class="text-[13px] text-[var(--text-muted)]">Register a new customer in the system</p>
      </div>
    </div>

    <!-- Customer Type Selection -->
    <UCard>
      <template #header>
        <p class="font-semibold text-[var(--text-primary)]">Customer Type</p>
      </template>
      <div class="flex gap-4">
        <div
          class="flex-1 border-2 rounded-xl p-4 text-center transition-all cursor-pointer"
          :class="[
            customerType === 'individual'
              ? 'border-primary-500 bg-primary-50'
              : 'border-gray-200 bg-[var(--surface)] hover:border-gray-300'
          ]"
          @click="customerType = 'individual'"
        >
          <UIcon name="i-heroicons-user" class="w-8 h-8 mx-auto mb-2" :class="customerType === 'individual' ? 'text-primary-500' : 'text-gray-400'" />
          <p class="font-medium text-sm" :class="customerType === 'individual' ? 'text-primary-700' : 'text-gray-600'">Individual</p>
        </div>
        <div
          class="flex-1 border-2 rounded-xl p-4 text-center transition-all cursor-pointer"
          :class="[
            customerType === 'corporate'
              ? 'border-primary-500 bg-primary-50'
              : 'border-gray-200 bg-[var(--surface)] hover:border-gray-300'
          ]"
          @click="customerType = 'corporate'"
        >
          <UIcon name="i-heroicons-building-office" class="w-8 h-8 mx-auto mb-2" :class="customerType === 'corporate' ? 'text-primary-500' : 'text-gray-400'" />
          <p class="font-medium text-sm" :class="customerType === 'corporate' ? 'text-primary-700' : 'text-gray-600'">Corporate</p>
        </div>
      </div>
    </UCard>

    <!-- Individual Form -->
    <template v-if="customerType === 'individual'">
      <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" />
            Personal Information
          </p>
        </template>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <UFormField label="First Name" required class="col-span-2 md:col-span-1">
            <UInput v-model="individualForm.first_name" placeholder="Juan" class="w-full" />
          </UFormField>
          <UFormField label="Last Name" required class="col-span-2 md:col-span-1">
            <UInput v-model="individualForm.last_name" placeholder="Pérez" class="w-full" />
          </UFormField>
          <UFormField label="Email" required>
            <UInput v-model="individualForm.email" type="email" placeholder="juan@example.com" class="w-full" />
          </UFormField>
          <UFormField label="Phone">
            <UInput v-model="individualForm.phone" placeholder="+507-1234-5678" class="w-full" />
          </UFormField>
          <UFormField label="Document ID" required>
            <UInput v-model="individualForm.document_id" placeholder="8-123-456" class="w-full" />
          </UFormField>
          <UFormField label="Date of Birth" required>
            <UInput v-model="individualForm.birth_date" type="date" class="w-full" />
          </UFormField>
          <UFormField label="Address" class="col-span-2">
            <UInput v-model="individualForm.address" placeholder="Calle 50, Panama City" class="w-full" />
          </UFormField>
        </div>
      </UCard>
    </template>

    <!-- Corporate Form -->
    <template v-else>
      <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" />
            Company Information
          </p>
        </template>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <UFormField label="Legal Name" required class="col-span-2">
            <UInput v-model="corporateForm.legal_name" placeholder="Empresa XYZ S.A." class="w-full" />
          </UFormField>
          <UFormField label="Commercial Name">
            <UInput v-model="corporateForm.commercial_name" placeholder="XYZ Corp" class="w-full" />
          </UFormField>
          <UFormField label="RUC" required>
            <UInput v-model="corporateForm.ruc" placeholder="123456-1-123456" class="w-full" />
          </UFormField>
          <UFormField label="Email" required>
            <UInput v-model="corporateForm.email" type="email" placeholder="contact@empresa.com" class="w-full" />
          </UFormField>
          <UFormField label="Phone">
            <UInput v-model="corporateForm.phone" placeholder="+507-1234-5678" class="w-full" />
          </UFormField>
          <UFormField label="Legal Representative Name" required>
            <UInput v-model="corporateForm.legal_rep_name" placeholder="Carlos López" class="w-full" />
          </UFormField>
          <UFormField label="Legal Representative Document ID" required>
            <UInput v-model="corporateForm.legal_rep_document_id" placeholder="8-789-012" class="w-full" />
          </UFormField>
          <UFormField label="Address" class="col-span-2">
            <UInput v-model="corporateForm.address" placeholder="Calle 100, Panama City" class="w-full" />
          </UFormField>
        </div>
      </UCard>
    </template>

    <!-- Submit -->
    <div class="flex justify-end gap-3">
      <NuxtLink to="/customers">
        <UButton color="gray" variant="soft">Cancel</UButton>
      </NuxtLink>
      <UButton
        color="primary"
        icon="i-heroicons-check"
        :loading="submitting"
        :disabled="!isValid"
        @click="submit"
      >
        Create Customer
      </UButton>
    </div>
  </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>
