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

async function fetchSubSpecialists(specialistId: string) {
  subspecialists.value = await getSubspecialistLabelList({
    serviceType: 1,
    serviceDate: new Date().toISOString().substring(0, 10),
    specialistCode: 0,
    "specialist-code": String(specialistId),
  }, true)
}

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

function handleSubSpecialistChange(selected: string) {
  selectedSubSpecialistId.value = selected ?? null
}

watch([selectedSpecialistId], () => {
  if (selectedSpecialistId.value) {
    fetchSubSpecialists(selectedSpecialistId.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"
    >
      Sub 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="subspecialists"
              :placeholder="placeholder"
              search-placeholder="Cari..."
              empty-message="Data tidak ditemukan"
              @update:model-value="handleSubSpecialistChange"
              :is-disabled="selectedSpecialistId === null"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
    </div>    
  </DE.Block>
</template>
