<script setup lang="ts">
// Components
import * as DE from '~/components/pub/my-ui/doc-entry'

// Types
import type { ConsultationFormData } from '~/schemas/consultation.schema.ts'

// Helpers
import type z from 'zod'
import { toTypedSchema } from '@vee-validate/zod'
import { useForm } from 'vee-validate'
import Textarea from '~/components/pub/ui/textarea/Textarea.vue'
import type { CreateDto } from '~/models/consultation'

interface Props {
  schema: z.ZodSchema<any>
  values: CreateDto
  encounter_id: number
  units: { value: string; label: string }[]
  isLoading?: boolean
  isReadonly?: boolean
}

const props = defineProps<Props>()
const isLoading = props.isLoading !== undefined ? props.isLoading : false
const isReadonly = props.isReadonly !== undefined ? props.isReadonly : false
const emit = defineEmits<{
  submit: [values: ConsultationFormData, resetForm: () => void]
  cancel: [resetForm: () => void]
}>()

const today = new Date()
const { defineField, errors, meta } = useForm({
  validationSchema: toTypedSchema(props.schema),
  initialValues: {
    date: props.values.date || today.toISOString().slice(0, 10),
    problem: '',
    dstUnit_id: 0,
  } as Partial<ConsultationFormData>,
})

const [date, dateAttrs] = defineField('date')
const [unit_id, unitAttrs] = defineField('unit_id')
const [problem, problemAttrs] = defineField('problem')

// Fill fields from props.values if provided
if (props.values) {
  if (props.values.date !== undefined) date.value = props.values.date.substring(0, 10)
  if (props.values.dstUnit_id !== undefined) unit_id.value = props.values.dstUnit_id
  if (props.values.problem !== undefined) problem.value = props.values.problem
}

const resetForm = () => {
  date.value = date.value ?? today.toISOString().slice(0, 10)
  unit_id.value = 0
  problem.value = ''
}

// Form submission handler
function onSubmitForm(values: any) {
  const formData: ConsultationFormData = {
    encounter_id: props.encounter_id,
    date: date.value ? `${date.value}T00:00:00Z` : '',
    problem: problem.value || '',
    dstUnit_id: unit_id.value || 0,
  }
  emit('submit', formData, resetForm)
}

// Form cancel handler
function onCancelForm() {
  emit('cancel', resetForm)
}
</script>

<template>
  <form id="form-division" @submit.prevent>
    <DE.Block labelSize="thin" class="!mb-2.5 !pt-0 xl:!mb-3" :colCount="3" :cellFlex="false">
      <DE.Cell>
        <DE.Label>Tanggal</DE.Label>
        <DE.Field :errMessage="errors.code">
          <Input
            v-model.number="date"
            icon-name="i-lucide-chevron-down"
            v-bind="dateAttrs"
            readonly
          />
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Unit</DE.Label>
        <DE.Field :errMessage="errors.unit_id">
          {{ errors.unit_id }}
          <Select
            id="strUnit_id"
            v-model.number="unit_id"
            icon-name="i-lucide-chevron-down"
            placeholder="Pilih kelompok obat"
            v-bind="unitAttrs"
            :items="props.units || []"
            :disabled="isLoading || isReadonly"
          />
          <!-- <Input type="number" id="unit_id" v-model.number="unit_id" v-bind="unitAttrs" :disabled="isLoading || isReadonly" /> -->
        </DE.Field>
      </DE.Cell>
      <DE.Cell :colSpan="3">
        <DE.Label>Uraian</DE.Label>
        <DE.Field :errMessage="errors.problem">
          <Textarea id="problem" v-model="problem" v-bind="problemAttrs" :disabled="isLoading || isReadonly" />
        </DE.Field>
      </DE.Cell>
    </DE.Block>
    <div class="my-2 flex justify-end gap-2 py-2">
      <Button type="button" variant="secondary" class="w-[120px]" @click="onCancelForm"> Kembali </Button>
      <Button
        v-if="!isReadonly"
        type="button"
        class="w-[120px]"
        :disabled="isLoading || !meta.valid"
        @click="onSubmitForm"
      >
        Simpan
      </Button>
    </div>
  </form>
</template>
