<script setup lang="ts">
import mockData from './sample'

// type
import { genDoctor, type Doctor } from '~/models/doctor'
import type { ActionReportFormData } from '~/schemas/action-report.schema'

// components
import { toast } from '~/components/pub/ui/toast'
import AppActionReportEntry from '~/components/app/action-report/entry-form.vue'
import ArrangementProcedurePicker from '~/components/app/therapy-protocol/picker-dialog/arrangement-procedure/procedure-picker.vue'

// states
const route = useRoute()
const { mode, goBack } = useQueryCRUDMode('mode')
const { recordId } = useQueryCRUDRecordId('record-id')
const reportData = ref<ActionReportFormData>({} as unknown as ActionReportFormData)
const doctors = ref<Doctor[]>([])
const isLoading = ref<boolean>(false)

// TODO: dummy data
;(() => {
  doctors.value = [genDoctor()]
})()

const entryMode = ref<'add' | 'edit' | 'view'>('add')
const isDataReady = ref(false)

onMounted(async () => {
  if (mode.value === 'entry' && recordId.value) {
    entryMode.value = 'edit'
    await loadEntryForEdit(+recordId.value)
  } else {
    // Untuk mode 'add', langsung set ready
    isDataReady.value = true
  }
})

// TODO: map data
async function loadEntryForEdit(id: number | string) {
  isLoading.value = true
  const result = mockData
  reportData.value = result as ActionReportFormData
  isLoading.value = false
  isDataReady.value = true
}
</script>

<template>
  <AppActionReportEntry
    v-if="isDataReady"
    :isLoading="isLoading"
    :mode="entryMode"
    @submit="(val) => console.log(val)"
    @back="goBack"
    @error="
      (err: Error) => {
        toast({
          title: 'Terjadi Kesalahan',
          description: err.message,
          variant: 'destructive',
        })
      }
    "
    :doctors="doctors"
    :initialValues="reportData"
  >
    <template #procedures>
      <ArrangementProcedurePicker
        field-name="procedures"
        title="Tindakan Operatif/Non-Operatif Lain"
        sub-title="Pilih Prosedur"
      />
    </template>
  </AppActionReportEntry>
  <div
    v-else
    class="flex items-center justify-center p-8"
  >
    <p class="text-muted-foreground">Memuat data...</p>
  </div>
</template>
