<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import Combobox from '~/components/pub/my-ui/combobox/combobox.vue'
import FieldGroup from '~/components/pub/my-ui/form/field-group.vue'
import Field from '~/components/pub/my-ui/form/field.vue'
import Label from '~/components/pub/my-ui/form/label.vue'
import { cn } from '~/lib/utils'

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

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

const {
  fieldName = 'provinceCode',
  placeholder = 'Pilih provinsi',
  errors,
  class: containerClass,
  fieldGroupClass,
} = props

// Gunakan composable untuk mengelola data provinces
const { provinceOptions, isLoading, error } = useProvinces()

// Computed untuk menentukan placeholder berdasarkan state
const dynamicPlaceholder = computed(() => {
  if (isLoading.value) return 'Memuat data provinsi...'
  if (error.value) return 'Gagal memuat data'
  return placeholder
})

// Computed untuk menentukan apakah field disabled
const isFieldDisabled = computed(() => {
  return props.isDisabled || isLoading.value || !!error.value
})
</script>

<template>
  <DE.Cell :class="cn('select-field-group', fieldGroupClass, containerClass)">
    <DE.Label
      :label-for="fieldName"
      :is-required="isRequired"
    >
      Provinsi
    </DE.Label>
    <DE.Field
      :id="fieldName"
      :errors="errors"
      :class="cn('select-field-wrapper')"
    >
      <FormField
        v-slot="{ componentField }"
        :name="fieldName"
      >
        <FormItem>
          <FormControl>
            <Combobox
              :id="fieldName"
              v-bind="componentField"
              :items="provinceOptions"
              :placeholder="dynamicPlaceholder"
              :is-disabled="isFieldDisabled"
              search-placeholder="Cari provinsi..."
              empty-message="Provinsi tidak ditemukan"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
  </DE.Cell>
</template>
