<script setup lang="ts">
import type { FormErrors } from '~/types/error'
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 { Input } from '~/components/pub/ui/input'
import { cn } from '~/lib/utils'

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

const props = defineProps<{
  fieldName: string
  placeholder: string
  label: string
  errors?: FormErrors
  class?: string
  colSpan?: number
  numericOnly?: boolean
  maxLength?: number
  isRequired?: boolean
  isDisabled?: boolean
}>()

function handleInput(event: Event) {
  const target = event.target as HTMLInputElement
  let value = target.value

  // Filter numeric only jika diperlukan
  if (props.numericOnly) {
    value = value.replace(/\D/g, '')
  }

  // Batasi panjang maksimal jika diperlukan
  if (props.maxLength && value.length > props.maxLength) {
    value = value.slice(0, props.maxLength)
  }

  // Update value jika ada perubahan
  if (target.value !== value) {
    target.value = value
    // Trigger input event untuk update form
    target.dispatchEvent(new Event('input', { bubbles: true }))
  }
}
</script>

<template>
  <DE.Cell :col-span="colSpan || 1">
    <DE.Label
      v-if="label !== ''"
      :label-for="fieldName"
      :is-required="isRequired && !isDisabled"
    >
      {{ label }}
    </DE.Label>
    <DE.Field
      :id="fieldName"
      :errors="errors"
    >
      <FormField
        v-slot="{ componentField }"
        :name="fieldName"
      >
        <FormItem>
          <FormControl>
            <Input
              :disabled="isDisabled"
              v-bind="componentField"
              :placeholder="placeholder"
              :maxlength="maxLength"
              :class="cn('focus:border-primary focus:ring-2 focus:ring-primary focus:ring-offset-0')"
              autocomplete="off"
              aria-autocomplete="none"
              autocorrect="off"
              autocapitalize="off"
              spellcheck="false"
              @input="handleInput"
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>
    </DE.Field>
  </DE.Cell>
</template>
