<script setup lang="ts">
import * as z from 'zod'
import Action from '~/components/pub/custom-ui/nav-footer/ba-su.vue'

const { errors, setFromZodError, clearErrors } = useFormErrors()

const data = ref({
  code: '',
  name: '',
  encounterClassCode: '',
})

const installation = {
  msg: {
    placeholder: '---pilih encounter class (fhir7)',
  },
  items: [
    { value: '1', label: 'Ambulatory', code: 'AMB' },
    { value: '2', label: 'Inpatient', code: 'IMP' },
    { value: '3', label: 'Emergency', code: 'EMER' },
    { value: '4', label: 'Observation', code: 'OBSENC' },
    { value: '5', label: 'Pre-admission', code: 'PRENC' },
    { value: '6', label: 'Short Stay', code: 'SS' },
    { value: '7', label: 'Virtual', code: 'VR' },
    { value: '8', label: 'Home Health', code: 'HH' },
  ],
}

const schema = z.object({
  name: z.string().min(1, 'Nama instalasi harus diisi'),
  code: z.string().min(1, 'Kode instalasi harus diisi'),
  encounterClassCode: z.string().min(1, 'Kelompok encounter class harus dipilih'),
})

function onClick(type: string) {
  if (type === 'cancel') {
    navigateTo('/org-src/instalasion')
  } else if (type === 'draft') {
    // do something
  } else if (type === 'submit') {
    // Clear previous errors
    clearErrors()

    const requestData = schema.safeParse(data.value)
    if (!requestData.success) {
      // Set errors menggunakan composable
      setFromZodError(requestData.error)

      // Optional: tampilkan toast notification untuk error general
      console.warn('Form validation failed:', requestData.error)
      return
    }

    console.log('Form data valid:', requestData.data)
    // do something with valid data
  }
}
</script>

<template>
  <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
    <Icon name="i-lucide-user" class="me-2" />
    <span class="font-semibold">Tambah</span> Instalasi
  </div>
  <div>
    <AppInstallationEntryForm v-model="data" :errors="errors" :encounter-class-code="installation" />
  </div>
  <div class="my-2 flex justify-end py-2">
    <Action @click="onClick" />
  </div>
</template>
