<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 type { Item } from '~/components/pub/my-ui/combobox'
import { getValueLabelList as getSpecialistLabelList } from '~/services/specialist.service'
import { getValueLabelList as getSubspecialistLabelList } from '~/services/subspecialist.service'

import * as DE from '~/components/pub/my-ui/doc-entry'

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 specialists = ref<Array<Item>>([])

async function fetchSpecialists(unitId: string) {
  specialists.value = await getSpecialistLabelList({
    serviceType: 1,
    serviceDate: new Date().toISOString().substring(0, 10),
    specialistCode: 0,
    "unit-id": String(unitId),
  }, true)
}

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

function handleSpecialistChange(selected: string) {
  selectedSpecialistId.value = selected ?? null
}

watch([selectedUnitId], () => {
  if (selectedUnitId.value) {
    fetchSpecialists(selectedUnitId.value)
  }
})
</script>

<template>
  <DE.Block :class="cn('select-field-group', fieldGroupClass, containerClass)">
    <div>
      <DE.Label
      :label-for="fieldName"
      :class="cn('select-field-label', labelClass)"
      :is-required="isRequired"
    >
      Spesialis
    </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="specialists"
              :placeholder="placeholder"
              search-placeholder="Cari..."
              empty-message="Data tidak ditemukan"
              @update:model-value="handleSpecialistChange"
              :is-disabled="selectedUnitId === null"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
    </div>
  </DE.Block>
</template>
