<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: '',
  parentId: '',
})

const division = {
  msg: {
    placeholder: '---pilih divisi utama',
    search: 'kode, nama divisi',
    empty: 'divisi tidak ditemukan',
  },
  items: [
    { value: '1', label: 'Medical', code: 'MED' },
    { value: '2', label: 'Nursing', code: 'NUR' },
    { value: '3', label: 'Admin', code: 'ADM' },
    { value: '4', label: 'Support', code: 'SUP' },
    { value: '5', label: 'Education', code: 'EDU' },
    { value: '6', label: 'Pharmacy', code: 'PHA' },
    { value: '7', label: 'Radiology', code: 'RAD' },
    { value: '8', label: 'Laboratory', code: 'LAB' },
    { value: '9', label: 'Finance', code: 'FIN' },
    { value: '10', label: 'Human Resources', code: 'HR' },
    { value: '11', label: 'IT Services', code: 'ITS' },
    { value: '12', label: 'Maintenance', code: 'MNT' },
    { value: '13', label: 'Catering', code: 'CAT' },
    { value: '14', label: 'Security', code: 'SEC' },
    { value: '15', label: 'Emergency', code: 'EMR' },
    { value: '16', label: 'Surgery', code: 'SUR' },
    { value: '17', label: 'Outpatient', code: 'OUT' },
    { value: '18', label: 'Inpatient', code: 'INP' },
    { value: '19', label: 'Rehabilitation', code: 'REB' },
    { value: '20', label: 'Research', code: 'RSH' },
  ],
}

const schema = z.object({
  name: z.string().min(1, 'Nama divisi harus diisi'),
  code: z.string().min(1, 'Kode divisi harus diisi'),
  parentId: z.preprocess(
    (input: unknown) => {
      if (typeof input === 'string') {
        // Handle empty string case
        if (input.trim() === '') {
          return 0
        }
        return Number(input)
      }

      return input
    },
    z.number().refine((num) => num > 0, 'Divisi harus dipilih'),
  ),
})

function onClick(type: string) {
  if (type === 'cancel') {
    navigateTo('/org-src/division')
  } 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> Divisi
  </div>
  <div>
    <AppDivisonEntryForm v-model="data" :errors="errors" :division="division" />
  </div>
  <div class="my-2 flex justify-end py-2">
    <Action @click="onClick" />
  </div>
</template>
