<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { computed } from 'vue';
import { toast } from 'vue-sonner';
import { RupiahInput } from '@/components/form/rupiah-input';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Textarea } from '@/components/ui/textarea';
import { useFormDialog } from '@/composables/useFormDialog';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import { parseRupiah } from '@/lib/rupiah';
import { store, update } from '@/routes/admin/finance/employee_advances';
import type { EmployeeAdvanceFormData, EmployeeAdvanceListItem } from '@/types/employee-advance';

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

const props = defineProps<{
    employeeAdvance?: EmployeeAdvanceListItem | null;
}>();

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

const form = useForm<EmployeeAdvanceFormData>({
    amount: '',
    description: '',
    due_date: '',
});

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

function populateForm(employeeAdvance: EmployeeAdvanceListItem | null | undefined) {
    resetForm();

    if (!employeeAdvance) {
        return;
    }

    form.amount = String(employeeAdvance.amount);
    form.description = employeeAdvance.description;
    form.due_date = employeeAdvance.due_date_input;
}

useFormDialog({
    open,
    source: () => props.employeeAdvance,
    populate: populateForm,
    reset: resetForm,
});

function buildFormData(forUpdate: boolean): FormData {
    const formData = new FormData();

    if (forUpdate) {
        formData.append('_method', 'PUT');
    }

    formData.append('amount', parseRupiah(form.amount));
    formData.append('description', form.description);
    formData.append('due_date', form.due_date);

    return formData;
}

function submit() {
    const payload = buildFormData(isEditing.value);

    const options = {
        forceFormData: true,
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    };

    if (isEditing.value && props.employeeAdvance) {
        form.transform(() => payload).put(update.url(props.employeeAdvance.id), options);

        return;
    }

    form.transform(() => payload).post(store.url(), options);
}
</script>

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

            <form @submit.prevent="submit">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="employee-advance-amount" required>Jumlah</FieldLabel>
                            <RupiahInput id="employee-advance-amount" v-model="form.amount" autofocus />
                            <FieldError :errors="formErrors(form, 'amount')" />
                        </Field>
                        <Field>
                            <FieldLabel for="employee-advance-description" required>Keterangan</FieldLabel>
                            <Textarea id="employee-advance-description" v-model="form.description"
                                placeholder="Contoh: Kebutuhan mendesak" rows="3"
                                :maxlength="FIELD_LIMITS.description" />
                            <FieldError :errors="formErrors(form, 'description')" />
                        </Field>
                        <Field>
                            <FieldLabel for="employee-advance-due-date" required>Jatuh Tempo</FieldLabel>
                            <DatePicker id="employee-advance-due-date" v-model="form.due_date" />
                            <FieldError :errors="formErrors(form, 'due_date')" />
                        </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...' : 'Ajukan' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
