<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { computed, watch } from 'vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { PhoneNumberInput } from '@/components/ui/phone-number-input';
import { Textarea } from '@/components/ui/textarea';
import type { CustomerFormData, CustomerListItem } from '@/types/customer';

const open = defineModel<boolean>('open', { default: false });

const props = defineProps<{
    customer?: CustomerListItem | null;
}>();

const isEditing = computed(() => props.customer != null);

const form = useForm<CustomerFormData>({
    name: '',
    phone_number: '',
    address: '',
});

function resetForm() {
    form.reset();
    form.clearErrors();
}

function populateForm(customer: CustomerListItem | null | undefined) {
    resetForm();

    if (!customer) {
        return;
    }

    form.name = customer.name;
    form.phone_number = customer.phone_number;
    form.address = customer.address;
}

watch(
    () => props.customer,
    (customer) => {
        populateForm(customer);
    },
);

watch(open, (isOpen) => {
    if (isOpen) {
        populateForm(props.customer);
    } else {
        resetForm();
    }
});

function submit() {
    const options = {
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: () => {
            toast.error('Gagal menyimpan data. Periksa kembali formulir.');
        },
    };

    if (isEditing.value && props.customer) {
        form.put(`/admin/master/customers/${props.customer.id}`, options);
    } else {
        form.post('/admin/master/customers', options);
    }
}
</script>

<template>
    <Dialog v-model:open="open">
        <DialogContent class="sm:max-w-md">
            <DialogHeader>
                <DialogTitle>{{ isEditing ? 'Ubah Customer' : 'Tambah Customer' }}</DialogTitle>
            </DialogHeader>

            <form @submit.prevent="submit">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="customer-name" required>Nama</FieldLabel>
                            <Input id="customer-name" v-model="form.name" type="text" placeholder="Nama customer"
                                autofocus />
                            <FieldError :errors="form.errors.name ? [form.errors.name] : []" />
                        </Field>
                        <Field>
                            <FieldLabel for="customer-phone-number" required>Nomor Telepon</FieldLabel>
                            <PhoneNumberInput id="customer-phone-number" v-model="form.phone_number"
                                placeholder="Nomor telepon customer" />
                            <FieldError :errors="form.errors.phone_number ? [form.errors.phone_number] : []" />
                        </Field>
                        <Field>
                            <FieldLabel for="customer-address" required>Alamat</FieldLabel>
                            <Textarea id="customer-address" v-model="form.address" rows="3"
                                placeholder="Alamat customer" />
                            <FieldError :errors="form.errors.address ? [form.errors.address] : []" />
                        </Field>
                    </FieldSet>
                </FieldGroup>

                <DialogFooter class="mt-6">
                    <Button type="button" variant="outline" :disabled="form.processing" @click="open = false">
                        Batal
                    </Button>
                    <Button type="submit" :disabled="form.processing">
                        <Save class="size-4" />
                        {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
