<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import Combobox from '~/components/pub/my-ui/combobox/combobox.vue'
import { cn, mapToComboboxOptList } from '~/lib/utils'
import { occupationCodes } from '~/lib/constants'
import { getValueLabelList as getDoctorLabelList } from '~/services/doctor.service'

import * as DE from '~/components/pub/my-ui/doc-entry'
import type { Item } from '~/components/pub/my-ui/combobox'

const props = defineProps<{
  fieldName?: string
  label?: string
  placeholder?: string
  errors?: FormErrors
  class?: string
  selectClass?: string
  fieldGroupClass?: string
  labelClass?: string
  isRequired?: boolean
}>()

const {
  fieldName = 'job',
  label = 'Pekerjaan',
  placeholder = 'Pilih pekerjaan',
  errors,
  class: containerClass,
  fieldGroupClass,
  labelClass,
} = props

const doctors = ref<Array<Item>>([])

async function fetchDpjp(specialistId: string, subspecialistId: string) {
  doctors.value = await getDoctorLabelList({
    serviceType: 1,
    serviceDate: new Date().toISOString().substring(0, 10),
    includes: 'employee-person',
    // "unit-id": parseInt(unitId),
    "specialist-code": String(specialistId),
    "subspecialist-code": String(subspecialistId),
  }, true)
}

// const selectedUnitId = inject<Ref<string | null>>("selectedUnitId")!
const selectedSpecialistId = inject<Ref<string | null>>("selectedSpecialistId")!
const selectedSubSpecialistId = inject<Ref<string | null>>("selectedSubSpecialistId")!

// function handleDpjpChange(selected: string) {
//   selectedDpjpId.value = selected ?? null
// }

watch([ selectedSpecialistId, selectedSubSpecialistId], () => {
  if (selectedSpecialistId.value && selectedSubSpecialistId.value) {
    console.log(`Select Doctor`)
    fetchDpjp( selectedSpecialistId.value, selectedSubSpecialistId.value)
  }
})
</script>

<template>
  <DE.Cell :class="cn('select-field-group', fieldGroupClass, containerClass)">
    <DE.Label
      :label-for="fieldName"
      :class="cn('select-field-label', labelClass)"
      :is-required="isRequired"
    >
      {{ label }}
    </DE.Label>
    <DE.Field
      :id="fieldName"
      :errors="errors"
      :class="cn('select-field-wrapper')"
    >
      <FormField
        v-slot="{ componentField }"
        :name="fieldName"
      >
        <FormItem>
          <FormControl>
            <Combobox
              class="focus:ring-0 focus:ring-offset-0"
              :id="fieldName"
              v-bind="componentField"
              :items="doctors"
              :placeholder="placeholder"
              search-placeholder="Cari..."
              empty-message="Data tidak ditemukan"
              :is-disabled="selectedSubSpecialistId === null"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
  </DE.Cell>
</template>
