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

const { fieldName = 'postalRegion', placeholder = 'Kode Pos', errors, class: containerClass, fieldGroupClass } = props

const villageCodeRef = toRef(props, 'villageCode')
const { postalRegionOptions, isLoading, error } = usePostalRegion(villageCodeRef)

const dynamicPlaceholder = computed(() => {
  if (!props.villageCode) return 'Pilih kelurahan terlebih dahulu'
  if (isLoading.value) return 'Memuat kode pos...'
  if (error.value) return 'Gagal memuat data'
  return placeholder
})

const isFieldDisabled = computed(() => {
  return props.isDisabled || !props.villageCode || isLoading.value || !!error.value
})
</script>

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