<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import Block from '~/components/pub/my-ui/doc-entry/block.vue'
import Cell from '~/components/pub/my-ui/doc-entry/cell.vue'
import Field from '~/components/pub/my-ui/doc-entry/field.vue'
import Label from '~/components/pub/my-ui/doc-entry/label.vue'
import Combobox from '~/components/pub/my-ui/combobox/combobox.vue'
import { Form } from '~/components/pub/ui/form'
import DatepickerSingle from '~/components/pub/my-ui/datepicker/datepicker-single.vue'

import { educationCodes, genderCodes, occupationCodes, religionCodes, relationshipCodes } from '~/lib/constants'
import { mapToComboboxOptList } from '~/lib/utils'

interface DivisionFormData {
  name: string
  code: string
  parentId: string
}

const props = defineProps<{
  division: {
    msg: {
      placeholder: string
      search: string
      empty: string
    }
  }
  items: {
    value: string
    label: string
    code: string
  }[]
  schema: any
  initialValues?: Partial<DivisionFormData>
  errors?: FormErrors
}>()

const emit = defineEmits<{
  submit: [values: DivisionFormData, resetForm: () => void]
  cancel: [resetForm: () => void]
  click: (e: Event) => void
}>()

const relationshipOpts = mapToComboboxOptList(relationshipCodes)
const educationOpts = mapToComboboxOptList(educationCodes)
const occupationOpts = mapToComboboxOptList(occupationCodes)
const genderOpts = mapToComboboxOptList(genderCodes)

const formSchema = toTypedSchema(props.schema)

// Form submission handler
function onSubmitForm(values: any, { resetForm }: { resetForm: () => void }) {
  const formData: DivisionFormData = {
    name: values.name || '',
    code: values.code || '',
    parentId: values.parentId || '',
  }
  emit('submit', formData, resetForm)
}
const doctorOpts = ref([
  { label: 'Pilih', value: null },
  { label: 'Dr. A', value: 1 },
])
const paymentOpts = ref([
  { label: 'Umum', value: 'umum' },
  { label: 'BPJS', value: 'bpjs' },
])
const sepOpts = ref([
  { label: 'Rujukan Internal', value: 'ri' },
  { label: 'SEP Rujukan', value: 'sr' },
])

// file refs untuk tombol "Pilih Berkas"
const sepFileInput = ref<HTMLInputElement | null>(null)
const sippFileInput = ref<HTMLInputElement | null>(null)

function pickSepFile() {
  sepFileInput.value?.click()
}
function pickSippFile() {
  sippFileInput.value?.click()
}

function onSepFileChange(e: Event) {
  const f = (e.target as HTMLInputElement).files?.[0]
  // set ke form / emit / simpan di state sesuai form library-mu
  console.log('sep file', f)
}

function onSippFileChange(e: Event) {
  const f = (e.target as HTMLInputElement).files?.[0]
  console.log('sipp file', f)
}

function onAddSep() {
  // contoh handler tombol "+" di sebelah No. SEP
  console.log('open modal tambah SEP')
}
</script>

<template>
  <Form
    v-slot="{ handleSubmit, resetForm }"
    as=""
    keep-values
    :validation-schema="formSchema"
    :initial-values="initialValues"
  >
    <form id="entry-form" @submit="handleSubmit($event, (values) => onSubmitForm(values, { resetForm }))">
      <div class="flex flex-col justify-between">
        <div class="mb-2 2xl:mb-3 text-sm 2xl:text-base font-semibold">
          Data Pasien
        </div>
        <div class="flex gap-6 mb-2 2xl:mb-2">
          <span>
            Sudah pernah terdaftar sebagai pasien?
            <Button class="bg-primary" size="sm" @click.prevent="emit('click', 'search')">
              <Icon name="i-lucide-search" class="mr-1" /> Cari Pasien
            </Button>
          </span>
          <span>
            Belum pernah terdaftar sebagai pasien?
            <Button class="bg-primary" size="sm" @click.prevent="emit('click', 'add')">
              <Icon name="i-lucide-plus" class="mr-1" /> Tambah Pasien Baru
            </Button>
          </span>
        </div>
        <Block :colCount="3">
          <Cell>
            <Label label-for="patient_name">Nama Pasien</Label>
            <Field id="patient_name" :errors="errors">
              <FormField v-slot="{ componentField }" name="patient_name">
                <FormItem>
                  <FormControl>
                    <Input
                      id="patient_name"
                      v-bind="componentField"
                      disabled
                      placeholder="Tambah data pasien terlebih dahulu"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- NIK -->
          <Cell :cosSpan="3">
            <Label label-for="nik">NIK</Label>
            <Field id="nik" :errors="errors">
              <FormField v-slot="{ componentField }" name="nik">
                <FormItem>
                  <FormControl>
                    <Input id="nik" v-bind="componentField" disabled placeholder="Otomatis" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>
          <Cell>
            <Label label-for="rm">No. RM</Label>
            <Field id="rm" :errors="errors">
              <FormField v-slot="{ componentField }" name="rm">
                <FormItem>
                  <FormControl>
                    <Input id="rm" v-bind="componentField" disabled placeholder="RM99222" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>
        </Block>

        <Separator class="my-4 2xl:my-5" />

        <div class="mb-2 2xl:mb-3 text-sm 2xl:text-base font-semibold">
          Data Kunjungan
        </div>
        <Block :colCount="3">
          <!-- Dokter (Combobox) -->
          <Cell :cosSpan="3">
            <Label label-for="doctor_id">Dokter</Label>
            <Field id="doctor_id" :errors="errors">
              <FormField v-slot="{ componentField }" name="doctor_id">
                <FormItem>
                  <FormControl>
                    <Combobox id="doctor_id" v-bind="componentField" :items="doctorOpts" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- Tanggal Daftar (DatePicker) -->
          <Cell :cosSpan="3">
            <Label label-for="register_date">Tanggal Daftar</Label>
            <Field id="register_date" :errors="errors">
              <FormField v-slot="{ componentField }" name="register_date">
                <FormItem>
                  <FormControl>
                    <DatepickerSingle v-bind="componentField" placeholder="Pilih tanggal" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- Jenis Pembayaran (Combobox) -->
          <Cell :cosSpan="3">
            <Label label-for="payment_type">Jenis Pembayaran</Label>
            <Field id="payment_type" :errors="errors">
              <FormField v-slot="{ componentField }" name="payment_type">
                <FormItem>
                  <FormControl>
                    <!-- <Combobox id="payment_type" v-bind="componentField" :items="paymentOpts" /> -->
                    <Select id="payment_type" v-bind="componentField" :items="paymentOpts" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>
        </Block>

        <Block :colCount="3">
          <Cell :cosSpan="3">
            <Label label-for="bpjs_number">Kelompok Peserta</Label>
            <Field id="bpjs_number" :errors="errors">
              <FormField v-slot="{ componentField }" name="bpjs_number">
                <FormItem>
                  <FormControl>
                    <Input
                      id="bpjs_number"
                      v-bind="componentField"
                      placeholder="Pilih jenis pembayaran terlebih dahulu"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- No. Kartu BPJS -->
          <Cell :cosSpan="3">
            <Label label-for="bpjs_number">No. Kartu BPJS</Label>
            <Field id="bpjs_number" :errors="errors">
              <FormField v-slot="{ componentField }" name="bpjs_number">
                <FormItem>
                  <FormControl>
                    <Input
                      id="bpjs_number"
                      v-bind="componentField"
                      placeholder="Pilih jenis pembayaran terlebih dahulu"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- Jenis SEP -->
          <Cell :cosSpan="3">
            <Label label-for="sep_type">Jenis SEP</Label>
            <Field id="sep_type" :errors="errors">
              <FormField v-slot="{ componentField }" name="sep_type">
                <FormItem>
                  <FormControl>
                    <Select id="sep_type" v-bind="componentField" :items="sepOpts" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>
        </Block>

        <Block :colCount="3">
          <!-- No. SEP (input + tombol +) -->
          <Cell :cosSpan="3">
            <Label label-for="sep_number">No. SEP</Label>
            <Field id="sep_number" :errors="errors">
              <FormField v-slot="{ componentField }" name="sep_number">
                <FormItem>
                  <FormControl>
                    <div class="flex gap-2">
                      <Input
                        id="sep_number"
                        v-bind="componentField"
                        placeholder="Tambah SEP terlebih dahulu"
                        class="flex-1"
                      />
                      <Button class="bg-primary" size="sm" variant="outline" @click.prevent="onAddSep">+</Button>
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- Dokumen SEP (file) -->
          <Cell :cosSpan="3">
            <Label label-for="sep_file">Dokumen SEP</Label>
            <Field id="sep_file" :errors="errors">
              <FormField v-slot="{ componentField }" name="sep_file">
                <FormItem>
                  <FormControl>
                    <div class="flex items-center gap-2">
                      <input ref="sepFileInput" type="file" class="hidden" @change="onSepFileChange" />
                      <Button class="bg-primary" size="sm" variant="ghost" @click.prevent="pickSepFile"
                        >Pilih Berkas</Button
                      >
                      <Input readonly v-bind="componentField" placeholder="Unggah dokumen SEP" />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>

          <!-- Dokumen SIPP (file) -->
          <Cell :cosSpan="3" labelSize="thin">
            <Label label-for="sipp_file">Dokumen SIPP</Label>
            <Field id="sipp_file" :errors="errors">
              <FormField v-slot="{ componentField }" name="sipp_file">
                <FormItem>
                  <FormControl>
                    <div class="flex items-center gap-2">
                      <input ref="sippFileInput" type="file" class="hidden" @change="onSippFileChange" />
                      <Button class="bg-primary" size="sm" variant="ghost" @click.prevent="pickSippFile"
                        >Pilih Berkas</Button
                      >
                      <Input readonly v-bind="componentField" placeholder="Unggah dokumen SIPP" />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </Cell>
        </Block>
      </div>
    </form>
  </Form>
</template>
