<script setup lang="ts">
import type { PersonFamilyFormData as FamilyData } from '~/schemas/person-family.schema'
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import { FieldArray } from 'vee-validate'
import SelectEducation from '~/components/app/patient/_common/select-education.vue'
import InputBase from '~/components/pub/my-ui/form/input-base.vue'
import RadioParentsInput from './_common/radio-parents-input.vue'
import { Form } from '~/components/pub/ui/form'

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

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

// Watcher untuk mengatur families ketika shareFamilyData berubah
watch(
  () => formRef.value?.values?.shareFamilyData,
  (newValue) => {
    if (newValue === '1' && formRef.value) {
      // Ketika memilih "Ya", pastikan ada data families untuk mother dan father
      const currentFamilies = formRef.value.values?.families || []
      if (currentFamilies.length === 0) {
        formRef.value.setFieldValue('families', [
          { relation: 'mother', name: undefined, education: undefined, occupation: undefined },
          { relation: 'father', name: undefined, education: undefined, occupation: undefined },
        ])
      }
    } else if (newValue === '0' && formRef.value) {
      // Ketika memilih "Tidak", kosongkan families
      formRef.value.setFieldValue('families', [])
    }
  },
  { immediate: false },
)

defineExpose({
  validate: () => formRef.value?.validate(),
  resetForm: () => formRef.value?.resetForm(),
  values: computed(() => formRef.value?.values),
})
</script>

<template>
  <Form
    ref="formRef"
    v-slot="{ values }"
    as=""
    keep-values
    :validation-schema="formSchema"
    :validate-on-mount="false"
    validation-mode="onSubmit"
    :initial-values="
      initialValues || {
        shareFamilyData: '0',
        families: [],
      }
    "
  >
    <div>
      <p
        v-if="props.title"
        class="text-sm 2xl:text-base mb-2 2xl:mb-3 font-semibold"
      >
        {{ props.title }}
      </p>
    </div>

    <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
      <!-- Radio Button Section - Full Width -->
      <div class="mb-6">
        <RadioParentsInput field-name="shareFamilyData" />
      </div>

      <!-- Form Fields Section - Only show when "Ya" is selected -->
      <div
        v-if="values.shareFamilyData === '1'"
        class="space-y-6"
      >
        <FieldArray
          v-slot="{ fields }"
          name="families"
        >
          <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <template
              v-for="(field, idx) in fields"
              :key="field.key"
            >
              <div
                class="space-y-4 rounded-lg border border-gray-200 bg-gray-50/50 p-4 dark:border-gray-700 dark:bg-gray-800/50"
              >
                <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300">
                  {{ (values.families as FamilyData[])?.[idx]?.relation === 'mother' ? 'Data Ibu' : 'Data Ayah' }}
                </h4>

                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div>
                    <InputBase
                      :field-name="`families[${idx}].name`"
                      :label="
                        (values.families as FamilyData[])?.[idx]?.relation === 'mother'
                          ? 'Nama Ibu Kandung'
                          : (values.families as FamilyData[])?.[idx]?.relation === 'father'
                            ? 'Nama Ayah Kandung'
                            : 'Nama Keluarga'
                      "
                      :placeholder="
                        (values.families as FamilyData[])?.[idx]?.relation === 'mother'
                          ? 'Masukkan nama ibu pasien'
                          : (values.families as FamilyData[])?.[idx]?.relation === 'father'
                            ? 'Masukkan nama ayah pasien'
                            : 'Masukkan nama'
                      "
                      :errors="errors"
                      is-required
                    />
                  </div>

                  <div>
                    <SelectEducation
                      :field-name="`families[${idx}].education`"
                      :label="
                        (values.families as FamilyData[])?.[idx]?.relation === 'mother'
                          ? 'Pendidikan Ibu'
                          : (values.families as FamilyData[])?.[idx]?.relation === 'father'
                            ? 'Pendidikan Ayah'
                            : 'Pendidikan'
                      "
                      placeholder="Pilih"
                      :errors="errors"
                    />
                  </div>
                </div>

                <div>
                  <InputBase
                    :field-name="`families[${idx}].occupation`"
                    :label="
                      (values.families as FamilyData[])?.[idx]?.relation === 'mother'
                        ? 'Pekerjaan Ibu'
                        : (values.families as FamilyData[])?.[idx]?.relation === 'father'
                          ? 'Pekerjaan Ayah'
                          : 'Pekerjaan'
                    "
                    :placeholder="
                      (values.families as FamilyData[])?.[idx]?.relation === 'mother'
                        ? 'Masukkan pekerjaan ibu'
                        : (values.families as FamilyData[])?.[idx]?.relation === 'father'
                          ? 'Masukkan pekerjaan ayah'
                          : 'Masukkan pekerjaan'
                    "
                    :errors="errors"
                  />
                </div>
              </div>
            </template>
          </div>
        </FieldArray>
      </div>
    </div>
  </Form>
</template>
