<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import FieldGroup from '~/components/pub/my-ui/form/field-group.vue'
import Field from '~/components/pub/my-ui/form/field.vue'
import InputBase from '~/components/pub/my-ui/form/input-base.vue'
import Label from '~/components/pub/my-ui/form/label.vue'
import SelectDistrict from './_common/select-district.vue'
import SelectPostal from './_common/select-postal.vue'
import SelectProvince from './_common/select-province.vue'
import SelectRegency from './_common/select-regency.vue'
import SelectVillage from './_common/select-village.vue'
import { Form } from '~/components/pub/ui/form'

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

const props = defineProps<{
  title: string
  conf?: {
    withAddressName?: boolean
  }
  schema: any
  initialValues?: any
  errors?: FormErrors
}>()

const formSchema = toTypedSchema(props.schema)
const formRef = ref()

defineExpose({
  validate: () => formRef.value?.validate(),
  resetForm: () => formRef.value?.resetForm(),
  setValues: (values: any, shouldValidate = true) => formRef.value?.setValues(values, shouldValidate),
  values: computed(() => formRef.value?.values),
})

// Watchers untuk cascading reset
let isResetting = false

// #region Watch provinceCode changes

watch(
  () => formRef.value?.values?.provinceCode,
  (newValue, oldValue) => {
    if (isResetting || !formRef.value || newValue === oldValue) return

    if (oldValue && newValue !== oldValue) {
      isResetting = true

      // Delay reset untuk memberikan waktu composable menyelesaikan request
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.setValues(
            {
              regencyId: undefined,
              districtId: undefined,
              villageId: undefined,
              zipCode: undefined,
            },
            false,
          )
        }

        nextTick(() => {
          isResetting = false
        })
      }, 150) // Delay 150ms, lebih dari debounce composable (100ms)
    }
  },
)

// Watch regencyId changes
watch(
  () => formRef.value?.values?.regencyId,
  (newValue, oldValue) => {
    if (isResetting || !formRef.value || newValue === oldValue) return

    if (oldValue && newValue !== oldValue) {
      isResetting = true

      // Delay reset untuk memberikan waktu composable menyelesaikan request
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.setValues(
            {
              districtId: undefined,
              villageId: undefined,
              zipCode: undefined,
            },
            false,
          )
        }

        nextTick(() => {
          isResetting = false
        })
      }, 150)
    }
  },
)

// Watch districtId changes
watch(
  () => formRef.value?.values?.districtId,
  (newValue, oldValue) => {
    if (isResetting || !formRef.value || newValue === oldValue) return

    if (oldValue && newValue !== oldValue) {
      isResetting = true

      // Delay reset untuk memberikan waktu composable menyelesaikan request
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.setValues(
            {
              villageId: undefined,
              zipCode: undefined,
            },
            false,
          )
        }

        nextTick(() => {
          isResetting = false
        })
      }, 150)
    }
  },
)

// Watch villageId changes
watch(
  () => formRef.value?.values?.villageId,
  (newValue, oldValue) => {
    if (isResetting || !formRef.value || newValue === oldValue) return

    if (oldValue && newValue !== oldValue) {
      isResetting = true

      formRef.value.setValues(
        {
          zipCode: undefined,
        },
        false,
      )

      nextTick(() => {
        isResetting = false
      })
    }
  },
)
// #endregion
</script>

<template>
  <Form
    ref="formRef"
    v-slot="{ values }"
    as=""
    keep-values
    :validation-schema="formSchema"
    :validate-on-mount="false"
    validation-mode="onSubmit"
    :initial-values="
      initialValues ? { locationType_code: 'domicile', ...initialValues } : { locationType_code: 'domicile' }
    "
  >
    <div>
      <p
        v-if="props.title"
        class="text-sm 2xl:text-base mb-2 2xl:mb-3 font-semibold"
      >
        {{ props.title }}
      </p>
    </div>
    <FormField
      v-slot="{ componentField }"
      name="locationType_code"
    >
      <input
        type="hidden"
        v-bind="componentField"
        value="domicile"
      />
    </FormField>

    <DE.Block :col-count="4" :cell-flex="false">
      <SelectProvince
        field-name="province_code"
        placeholder="Pilih"
        is-required
      />
      <SelectRegency
        field-name="regency_code"
        :province-code="values.province_code"
        is-required
      />
      <SelectDistrict
        field-name="district_code"
        :regency-code="values.regency_code"
        is-required
      />
      <SelectVillage
        field-name="village_code"
        :district-code="values.district_code"
        is-required
      />
      <InputBase
        field-name="address"
        label="Alamat"
        placeholder="Masukkan alamat"
        :errors="errors"
        is-required
        :col-span="2"
      />
      <DE.Cell class="flex-row gap-2">
        <div class="grid grid-cols-2 gap-1">
          <InputBase
            field-name="rt"
            label="RT"
            placeholder="01"
            :errors="errors"
            numeric-only
            :max-length="2"
            />
          <InputBase
            field-name="rw"
            label="RW"
            placeholder="02"
            :errors="errors"
            :max-length="2"
            numeric-only
          />
        </div>
      </DE.Cell>
      <SelectPostal
          field-name="postalRegion_code"
          placeholder="Pilih kelurahan dahulu"
          :village-code="values.village_code"
          :is-disabled="!values.village_code"
        />
    </DE.Block>
  </Form>
</template>
