<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
  provinceCode?: string
  isDisabled?: boolean
  placeholder?: string
  errors?: FormErrors
  class?: string
  selectClass?: string
  fieldGroupClass?: string
  isRequired?: boolean
}>()

const {
  fieldName = 'regencyId',
  placeholder = 'Pilih kabupaten/kota',
  errors,
  class: containerClass,
  fieldGroupClass,
} = props

// Gunakan composable untuk mengelola data regencies
const provinceCodeRef = toRef(props, 'provinceCode')
const { regencyOptions, isLoading, error } = useRegencies({ provinceCode: provinceCodeRef, enablePagination: false })

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

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

<template>
  <DE.Cell :class="cn('select-field-group', fieldGroupClass, containerClass)">
    <DE.Label
      :label-for="fieldName"
      :is-required="isRequired"
    >
      Kabupaten/Kota
    </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="regencyOptions"
              :placeholder="dynamicPlaceholder"
              :is-disabled="isFieldDisabled"
              search-placeholder="Cari kabupaten/kota..."
              empty-message="Kabupaten/kota tidak ditemukan"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
  </DE.Cell>
</template>
