<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 getUnitLabelList } from '~/services/unit.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 units = ref<Array<Item>>([])

async function fetchData() {
  units.value = await getUnitLabelList({}, true)
}

const selectedUnitId = inject<Ref<string | null>>("selectedUnitId")!
function handleDataChange(selected: string) {
  selectedUnitId.value = selected ?? null
}

onMounted(() => {
  fetchData()
})
</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="units"
              :placeholder="placeholder"
              search-placeholder="Cari..."
              empty-message="Data tidak ditemukan"
              @update:model-value="handleDataChange"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
  </DE.Cell>
</template>
