<script setup>
import { ref } from 'vue';
import CreateDialog from '@/Components/Dialogs/CreateDialog.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 SectionTitle from '@/Components/SectionTitle.vue';
import ActionMessage from '@/Components/ActionMessage.vue';
import {
  FormControl,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/Components/ui/form";
import { Input } from "@/Components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";

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

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

const close = () => {
    form.resetForm();
    emit('close');
}

const formSchema = toTypedSchema(
  z.object({
    client_uuid: z.string(),
    person: z.object({
      first_name: z.string().optional(),
      last_name: z.string().optional(),
      full_name: z.string().min(1, "Naziv je obvezen."),
      tax_number: z.string().optional(),
      social_security_number: z.string().optional(),
      description: z.string().optional(),
      address: z.object({
        address: z.string().optional(),
        country: z.string().optional(),
        type_id: z.number().default(1),
      }),
      phone: z.object({
        nu: z.string().optional(),
        country_code: z.string().default('00386'),
        type_id: z.number().default(1),
      }),
    }),
  })
);

const form = useForm({
  validationSchema: formSchema,
  initialValues: {
    client_uuid: props.clientUuid,
    person: {
      first_name: '',
      last_name: '',
      full_name: '',
      tax_number: '',
      social_security_number: '',
      description: '',
      address: {
        address: '',
        country: '',
        type_id: 1
      },
      phone: {
        nu: '',
        country_code: '00386',
        type_id: 1
      }
    }
  },
});

const processing = ref(false);

const storeCase = async () => {
  processing.value = true;
  const { values } = form;

  router.post(
    route('clientCase.store'),
    values,
    {
      onSuccess: () => {
        close();
        form.resetForm();
        processing.value = false;
      },
      onError: (errors) => {
        Object.keys(errors).forEach((field) => {
          const errorMessages = Array.isArray(errors[field])
            ? errors[field]
            : [errors[field]];
          // Handle nested field paths like "person.full_name"
          const fieldPath = field.includes('.') ? field : field;
          form.setFieldError(fieldPath, errorMessages[0]);
        });
        processing.value = false;
      },
      onFinish: () => {
        processing.value = false;
      },
    }
  );
};

const onConfirm = form.handleSubmit(() => {
  storeCase();
});
</script>
<template>
    <CreateDialog
        :show="show"
        title="Nova primer"
        confirm-text="Shrani"
        :processing="processing"
        @close="close"
        @confirm="onConfirm"
    >
        <form @submit.prevent="onConfirm">
            <SectionTitle class="border-b mb-4">
                <template #title>
                    Oseba
                </template>
            </SectionTitle>

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

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

                    <FormField v-slot="{ componentField }" name="person.social_security_number">
                        <FormItem>
                            <FormLabel>Matična / Emšo</FormLabel>
                            <FormControl>
                                <Input 
                                    id="socialSecurityNumber"
                                    type="text"
                                    placeholder="Matična / Emšo"
                                    autocomplete="social-security-number"
                                    v-bind="componentField"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ componentField }" name="person.address.address">
                        <FormItem>
                            <FormLabel>Naslov</FormLabel>
                            <FormControl>
                                <Input 
                                    id="address"
                                    type="text"
                                    placeholder="Naslov"
                                    autocomplete="street-address"
                                    v-bind="componentField"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ componentField }" name="person.address.country">
                        <FormItem>
                            <FormLabel>Država</FormLabel>
                            <FormControl>
                                <Input 
                                    id="addressCountry"
                                    type="text"
                                    placeholder="Država"
                                    autocomplete="country"
                                    v-bind="componentField"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ value, handleChange }" name="person.address.type_id">
                        <FormItem>
                            <FormLabel>Vrsta naslova</FormLabel>
                            <Select :model-value="value" @update:model-value="handleChange">
                                <FormControl>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Izberi vrsto" />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    <SelectItem :value="1">Stalni</SelectItem>
                                    <SelectItem :value="2">Začasni</SelectItem>
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ value, handleChange }" name="person.phone.country_code">
                        <FormItem>
                            <FormLabel>Koda države tel.</FormLabel>
                            <Select :model-value="value" @update:model-value="handleChange">
                                <FormControl>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Izberi kodo" />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    <SelectItem value="00386">+386 (Slovenija)</SelectItem>
                                    <SelectItem value="00385">+385 (Hrvaška)</SelectItem>
                                    <SelectItem value="0039">+39 (Italija)</SelectItem>
                                    <SelectItem value="0036">+36 (Madžarska)</SelectItem>
                                    <SelectItem value="0043">+43 (Avstrija)</SelectItem>
                                    <SelectItem value="00381">+381 (Srbija)</SelectItem>
                                    <SelectItem value="00387">+387 (Bosna in Hercegovina)</SelectItem>
                                    <SelectItem value="00382">+382 (Črna gora)</SelectItem>
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ componentField }" name="person.phone.nu">
                        <FormItem>
                            <FormLabel>Telefonska št.</FormLabel>
                            <FormControl>
                                <Input 
                                    id="phoneNu"
                                    type="text"
                                    placeholder="Telefonska številka"
                                    autocomplete="tel"
                                    v-bind="componentField"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    </FormField>

                    <FormField v-slot="{ componentField }" name="person.description">
                        <FormItem>
                            <FormLabel>Opis</FormLabel>
                            <FormControl>
                                <Input 
                                    id="description"
                                    type="text"
                                    placeholder="Opis"
                                    autocomplete="off"
                                    v-bind="componentField"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    </FormField>
                </div>
            </form>
    </CreateDialog>
</template>
