<script setup lang="ts">
const router = useRouter()
const submitting = ref(false)
const toast = useToast()
const { $providers } = useNuxtApp()

const form = ref({
  name: '', email: '', phone: '', contact_name: '', ruc: '', address: ''
})

const isValid = computed(() => form.value.name && form.value.email)

async function submit() {
  submitting.value = true
  try {
    const data = await $providers('/providers', { method: 'POST', body: form.value }) as any
    toast.add({ title: 'Provider created', color: 'green' })
    router.push(`/providers/${data.provider_id}`)
  } catch (e: any) {
    toast.add({ title: 'Failed to create provider', 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">
    <div class="flex items-center gap-4">
      <NuxtLink to="/providers">
        <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">Back</UButton>
      </NuxtLink>
      <div>
        <h1 class="text-3xl font-bold text-slate-900">New Provider</h1>
        <p class="text-gray-500 text-sm">Register a new insurance carrier</p>
      </div>
    </div>

    <UCard 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" /> Provider Information
        </p>
      </template>

      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <UFormField label="Company Name" required class="col-span-2">
            <UInput v-model="form.name" placeholder="Seguros Panama S.A." class="w-full" />
          </UFormField>
          <UFormField label="Email" required>
            <UInput v-model="form.email" type="email" placeholder="cotizaciones@seguros.com" class="w-full" />
          </UFormField>
          <UFormField label="Phone">
            <UInput v-model="form.phone" placeholder="+507 300-0000" class="w-full" />
          </UFormField>
          <UFormField label="Contact Name">
            <UInput v-model="form.contact_name" placeholder="María García" class="w-full" />
          </UFormField>
          <UFormField label="RUC">
            <UInput v-model="form.ruc" placeholder="1234567-1-123456" class="w-full" />
          </UFormField>
          <UFormField label="Address" class="col-span-2">
            <UInput v-model="form.address" placeholder="Av. Balboa, Panama City" class="w-full" />
          </UFormField>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-3">
          <NuxtLink to="/providers"><UButton color="gray" variant="soft">Cancel</UButton></NuxtLink>
          <UButton color="primary" icon="i-heroicons-check" :loading="submitting" :disabled="!isValid" @click="submit">
            Create Provider
          </UButton>
        </div>
      </template>
    </UCard>
  </div>
</template>
