<script setup lang="ts">
import ProcedureListDialog from './form.vue'
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import { FieldArray } from 'vee-validate'
import InputBase from '~/components/pub/my-ui/form/input-base.vue'
import TextAreaInput from '~/components/pub/my-ui/form/text-area-input.vue'
import { cn } from '~/lib/utils'
import TableHeader from '~/components/pub/ui/table/TableHeader.vue'
import { is } from 'date-fns/locale'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import List from './form.vue'
import { getValueLabelList as getMedicineFormList } from '~/services/medicine-form.service'
import { getValueLabelList as getMedicineList } from '~/services/medicine.service'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import * as DE from '~/components/pub/my-ui/doc-entry'
import FormEntry from './form.vue'
import { PrbSchema } from '~/schemas/prb.schema'
import type { ExposedForm } from '~/types/form'
import type { Prb } from '~/models/prb'
import { PrbMedicineSchema } from '~/schemas/prb-medicine.schema'

interface Props {
  fieldName: string
  title: string
}
const props = defineProps<Props>()
const isOperativeActionDialogOpen = ref(false)
provide("isOperativeActionDialogOpen", isOperativeActionDialogOpen);

const inputForm = ref<ExposedForm<any> | null>(null)
const medicine = ref<{ value: string; label: string }[]>([])
const medicineForms = ref<{ value: string; label: string }[]>([])

const handleToggleOperativeActionDialog = () => {
  isOperativeActionDialogOpen.value = !isOperativeActionDialogOpen.value
}

async function init(){
  const [medicineRes, medicineFormRes] = await Promise.all([
    getMedicineList({ sort: 'createdAt:asc', }),
    getMedicineFormList({ sort: 'createdAt:asc', })
  ])
  medicine.value = medicineRes 
  medicineForms.value = medicineFormRes 
}

onMounted(()=>{
  init()
})

async function handleAdd(psuhFn: (input: unknown) => void) {
  const validated = await composeFormData()
  psuhFn({
    code: validated.a1,
    name: validated.a2,
    signa: validated.a3,
    total: validated.a5,
    duration: validated.a6,
  })
  handleToggleOperativeActionDialog()
}

async function composeFormData(): Promise<any> {
  const [input,] = await Promise.all([
    inputForm.value?.validate(),
  ])

  const results = [input]
  const allValid = results.every((r) => r?.valid)

  // exit, if form errors happend during validation
  if (!allValid) return Promise.reject('Form validation failed')

  const formData = input?.values
  return new Promise((resolve) => resolve(formData))
}
</script>

<template>
  <div class="">
    <div class="mb-2 flex items-center gap-3">
      <h1 class="font-medium text-base">{{ title }}</h1>
      <Button @click="isOperativeActionDialogOpen = true" size="xs" variant="outline"
        class="rounded-lg text-orange-400 border-orange-400 bg-transparent">
        <Icon name="i-lucide-search" class="h-4 w-4 align-middle transition-colors" />
        Pilih {{ title }}
      </Button>
    </div>

    <FieldArray v-slot="{ fields, push, remove }" :name="props.fieldName">
      <Dialog
        v-model:open="isOperativeActionDialogOpen"
        title="" size="xl">
        <FormEntry
          ref="inputForm"
          :schema="PrbMedicineSchema"
          :medicine-data="medicine"
          :medicine-forms-data="medicineForms"
          @toggle-dialog="handleToggleOperativeActionDialog"
        />
        <div class="mt-2 flex justify-end">
          <Button @click="handleAdd(push)" class="">
            <Icon name="i-lucide-save" class="h-4 w-4 align-middle transition-colors" />
            Simpan
          </Button>
        </div>
      </Dialog>

      <div class="border border-gray-200 rounded-lg overflow-hidden">
        <Table>
          <TableHeader class="bg-gray-100">
            <TableRow>
              <TableHead class="">Code</TableHead>
              <TableHead class="">Name</TableHead>
              <TableHead class="">Signa</TableHead>
              <TableHead class="">Jumlah</TableHead>
              <TableHead class="">Durasi Pemberian</TableHead>
              <TableHead class="w-24">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow v-for="(field, idx) in fields" :key="idx">
              <TableCell class="2xl:pl-4">{{ field.value?.code }}</TableCell>
              <TableCell class="2xl:pl-4">{{ field.value?.name }}</TableCell>
              <TableCell class="2xl:pl-4">{{ field.value?.signa }}</TableCell>
              <TableCell class="2xl:pl-4">{{ field.value?.total }}</TableCell>
              <TableCell class="2xl:pl-4">{{ field.value?.duration }}</TableCell>
              <TableCell class="2xl:pl-4">
                <Button type="button" variant="destructive" size="sm" @click="remove(idx)">
                  <Icon name="i-lucide-trash-2" class="h-4 w-4" />
                </Button>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </div>
    </FieldArray>
  </div>
</template>
