<script setup>
import UpdateDialog from '@/Components/Dialogs/UpdateDialog.vue';
import SectionTitle from '@/Components/SectionTitle.vue';
import { useForm, Field as FormField } from "vee-validate";
import { toTypedSchema } from "@vee-validate/zod";
import * as z from "zod";
import { router } from '@inertiajs/vue3';
import { ref } from 'vue';
import {
  FormControl,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/Components/ui/form";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    person: Object
});

const processingUpdate = ref(false);

const emit = defineEmits(['close']);

const formSchema = toTypedSchema(
  z.object({
    full_name: z.string().min(1, "Naziv je obvezen."),
    tax_number: z.string().optional(),
    social_security_number: z.string().optional(),
    description: z.string().optional(),
  })
);

const form = useForm({
  validationSchema: formSchema,
  initialValues: {
    full_name: props.person?.full_name || '',
    tax_number: props.person?.tax_number || '',
    social_security_number: props.person?.social_security_number || '',
    description: props.person?.description || ''
  },
});

const close = () => {
    emit('close');
    setTimeout(() => {
        form.resetForm({
          values: {
            full_name: props.person?.full_name || '',
            tax_number: props.person?.tax_number || '',
            social_security_number: props.person?.social_security_number || '',
            description: props.person?.description || ''
          }
        });
    }, 500);
}

const updatePerson = async () => {
    processingUpdate.value = true;
    const { values } = form;

    router.put(
      route('person.update', props.person),
      values,
      {
        preserveScroll: true,
        onSuccess: () => {
          processingUpdate.value = false;
          close();
        },
        onError: (errors) => {
          // Map Inertia errors to VeeValidate field errors
          Object.keys(errors).forEach((field) => {
            const errorMessages = Array.isArray(errors[field])
              ? errors[field]
              : [errors[field]];
            form.setFieldError(field, errorMessages[0]);
          });
          processingUpdate.value = false;
        },
        onFinish: () => {
          processingUpdate.value = false;
        },
      }
    );
}

const onSubmit = form.handleSubmit(() => {
  updatePerson();
});

const onConfirm = () => {
    onSubmit();
}
</script>
<template>
    <UpdateDialog
        :show="show"
        :title="`Posodobi ${person.full_name}`"
        confirm-text="Shrani"
        :processing="processingUpdate"
        @close="close"
        @confirm="onConfirm"
    >
        <form @submit.prevent="onSubmit">
            <SectionTitle class="border-b mb-4">
                <template #title>
                    Oseba
                </template>
            </SectionTitle>

            <div class="space-y-4">
                <FormField v-slot="{ componentField }" name="full_name">
                    <FormItem>
                        <FormLabel>Naziv</FormLabel>
                        <FormControl>
                            <Input 
                                id="cfullname"
                                type="text"
                                placeholder="Naziv"
                                autocomplete="full-name"
                                v-bind="componentField"
                            />
                        </FormControl>
                        <FormMessage />
                    </FormItem>
                </FormField>

                <FormField v-slot="{ componentField }" name="tax_number">
                    <FormItem>
                        <FormLabel>Davčna</FormLabel>
                        <FormControl>
                            <Input 
                                id="ctaxnumber"
                                type="text"
                                placeholder="Davčna številka"
                                autocomplete="tax-number"
                                v-bind="componentField"
                            />
                        </FormControl>
                        <FormMessage />
                    </FormItem>
                </FormField>

                <FormField v-slot="{ componentField }" name="social_security_number">
                    <FormItem>
                        <FormLabel>Matična / Emšo</FormLabel>
                        <FormControl>
                            <Input 
                                id="csocialSecurityNumber"
                                type="text"
                                placeholder="Matična / Emšo"
                                autocomplete="social-security-number"
                                v-bind="componentField"
                            />
                        </FormControl>
                        <FormMessage />
                    </FormItem>
                </FormField>
                
                <FormField v-slot="{ componentField }" name="description">
                    <FormItem>
                        <FormLabel>Opis</FormLabel>
                        <FormControl>
                            <Textarea 
                                id="cdescription"
                                placeholder="Opis"
                                v-bind="componentField"
                            />
                        </FormControl>
                        <FormMessage />
                    </FormItem>
                </FormField>
            </div>
        </form>
    </UpdateDialog>
</template>
