<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 Label from '~/components/pub/my-ui/form/label.vue'
import Select from '~/components/pub/my-ui/form/select.vue'
import { Form } from '~/components/pub/ui/form'
import InputBase from '~/components/pub/my-ui/form/input-base.vue'
import type { InstallationFormData } from '~/schemas/installation.schema'
import TextCaptcha from '~/components/pub/my-ui/form/text-captcha.vue'


const props = defineProps<{
  schema: any
  errors?: FormErrors
}>()

const emit = defineEmits<{
  submit: [values: InstallationFormData, resetForm: () => void]
  cancel: [resetForm: () => void]
}>()

const formSchema = toTypedSchema(props.schema)
const captchaRef = ref<InstanceType<typeof TextCaptcha> | null>(null)

// Form submission handler
function onSubmitForm(values: any, { resetForm }: { resetForm: () => void }) {
  const formData: InstallationFormData = {
    name: values.name || '',
    code: values.code || '',
  }
  emit('submit', formData, resetForm)
}

// Form cancel handler
function onCancelForm({ resetForm }: { resetForm: () => void }) {
  emit('cancel', resetForm)
}

const items = ref([
  { label: 'Rujukan Internal', value: 'ri' },
  { label: 'SEP Rujukan', value: 'sr' },
])
</script>

<template>
  <Form
    v-slot="{ handleSubmit, resetForm }"
    as=""
    keep-values
    :validation-schema="formSchema"
  >
    <form id="entry-form" @submit="handleSubmit($event, (values) => onSubmitForm(values, { resetForm }))">
      <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
        <div class="flex flex-col justify-between">

          <InputBase
            field-name="name"
            label="Nama"
            placeholder="Masukkan Nama"
            :errors="errors"/>
          <InputBase
            field-name="email"
            label="Email"
            placeholder="Masukkan Email"
            :errors="errors"/>

          <div class="mt-2">
            <Label class="" for="password">Password</Label>
            <Field class="" id="password" :errors="errors">
              <FormField v-slot="{ componentField }" name="password">
                <FormItem>
                  <FormControl>
                    <Input
                      id="password"
                      v-bind="componentField"
                      type="password"
                      class="w-full"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              </FormField>
            </Field>
          </div>

          <TextCaptcha
            ref="captchaRef"
            :length="5"
            :useSpacing="true"
            :noiseChars="true"/>

        </div>
      </div>
    </form>
  </Form>
</template>