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

// individual form
const individualForm = ref({
  first_name:  '',
  last_name:   '',
  email:       '',
  phone:       '',
  birth_date:  '',
  gender:      '',
  document_id: ''
})

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

const genderItems = ref<SelectItem[]>([
  { label: 'Male',   value: 'male'   },
  { label: 'Female', value: 'female' }
])

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

async function submit() {
  submitting.value = true
  try {
    const isIndividual = customerType.value === 'individual'
    const data = await $customer(isIndividual ? '/customers' : '/customers/corporate', {
      method: 'POST',
      body:   isIndividual ? individualForm.value : corporateForm.value
    }) as any
    toast.add({ title: 'Customer created successfully', color: 'green' })
    router.push(`/customers/${data.data.id}`)
  } catch (e: any) {
    toast.add({
      title:       'Failed to create customer',
      description: e?.data?.errors ? JSON.stringify(e.data.errors) : e.message,
      color:       'red'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <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-3xl text-slate-900 font-bold">New Customer</h1>
        <p class="text-gray-500 text-sm">Create a new customer record</p>
      </div>
    </div>

    <!-- Type selector -->
    <div class="flex gap-4 max-w-2xl">
      <div
        v-for="type in ['individual', 'corporate']"
        :key="type"
        class="flex-1 border-2 rounded-xl p-4 text-center transition-all cursor-pointer"
        :class="customerType === type
          ? 'border-primary-500 bg-primary-50'
          : 'border-gray-200 bg-white hover:border-gray-300'"
        @click="customerType = type as any"
      >
        <UIcon
          :name="type === 'individual' ? 'i-heroicons-user' : 'i-heroicons-building-office'"
          class="w-8 h-8 mx-auto mb-2"
          :class="customerType === type ? 'text-primary-500' : 'text-gray-400'"
        />
        <p
          class="font-medium text-sm"
          :class="customerType === type ? 'text-primary-700' : 'text-gray-600'"
        >
          {{ type === 'individual' ? 'Individual' : 'Corporate' }}
        </p>
      </div>
    </div>

    <!-- Individual form -->
    <UCard v-if="customerType === 'individual'" class="max-w-2xl">
      <template #header>
        <p class="font-semibold text-slate-700 flex items-center gap-2">
          <UIcon name="i-heroicons-user-plus" class="w-4 h-4" />
          Individual Customer
        </p>
      </template>

      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <UFormField label="First Name" required>
            <UInput v-model="individualForm.first_name" placeholder="Juan" class="w-full" />
          </UFormField>
          <UFormField label="Last Name" required>
            <UInput v-model="individualForm.last_name" placeholder="Pérez" class="w-full" />
          </UFormField>
        </div>

        <UFormField label="Document ID" required>
          <UInput
            v-model="individualForm.document_id"
            placeholder="V-12345678"
            icon="i-heroicons-identification"
            class="w-full"
          />
        </UFormField>

        <UFormField label="Email" required>
          <UInput
            v-model="individualForm.email"
            type="email"
            placeholder="juan@example.com"
            icon="i-heroicons-envelope"
            class="w-full"
          />
        </UFormField>

        <UFormField label="Phone">
          <UInput
            v-model="individualForm.phone"
            placeholder="+507 6000-0000"
            icon="i-heroicons-phone"
            class="w-full"
          />
        </UFormField>

        <div class="grid grid-cols-2 gap-4">
          <UFormField label="Birth Date">
            <UInput v-model="individualForm.birth_date" type="date" class="w-full" />
          </UFormField>
          <UFormField label="Gender">
            <USelect v-model="individualForm.gender" :items="genderItems" class="w-full" />
          </UFormField>
        </div>
      </div>

      <template #footer>
        <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>
      </template>
    </UCard>

    <!-- Corporate form -->
    <UCard v-else class="max-w-2xl">
      <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" />
          Corporate Customer
        </p>
      </template>

      <div class="space-y-4">
        <UFormField label="Legal Name" required>
          <UInput
            v-model="corporateForm.legal_name"
            placeholder="Empresa S.A."
            icon="i-heroicons-building-office"
            class="w-full"
          />
        </UFormField>

        <UFormField label="Commercial Name">
          <UInput
            v-model="corporateForm.commercial_name"
            placeholder="Empresa"
            class="w-full"
          />
        </UFormField>

        <UFormField label="RUC" required>
          <UInput
            v-model="corporateForm.ruc"
            placeholder="1234567-1-123456"
            icon="i-heroicons-identification"
            class="w-full"
          />
        </UFormField>

        <div class="grid grid-cols-2 gap-4">
          <UFormField label="Legal Representative">
            <UInput
              v-model="corporateForm.legal_rep_name"
              placeholder="Juan Pérez"
              class="w-full"
            />
          </UFormField>
          <UFormField label="Legal Rep Document ID">
            <UInput
              v-model="corporateForm.legal_rep_document_id"
              placeholder="V-12345678"
              class="w-full"
            />
          </UFormField>
        </div>

        <UFormField label="Email">
          <UInput
            v-model="corporateForm.email"
            type="email"
            placeholder="contacto@empresa.com"
            icon="i-heroicons-envelope"
            class="w-full"
          />
        </UFormField>

        <UFormField label="Phone">
          <UInput
            v-model="corporateForm.phone"
            placeholder="+507 300-0000"
            icon="i-heroicons-phone"
            class="w-full"
          />
        </UFormField>

        <UFormField label="Address">
          <UInput
            v-model="corporateForm.address"
            placeholder="Av. Balboa, Panama City"
            icon="i-heroicons-map-pin"
            class="w-full"
          />
        </UFormField>
      </div>

      <template #footer>
        <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 Corporate Customer
          </UButton>
        </div>
      </template>
    </UCard>
  </div>
</template>
