<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 { RupiahInput } from '@/components/ui/rupiah-input';
import { Textarea } from '@/components/ui/textarea';
import { parseRupiah } from '@/lib/rupiah';
import type { ExpenseFormData, ExpenseListItem } from '@/types/expense';

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

const props = defineProps<{
    expense?: ExpenseListItem | null;
}>();

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

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

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

function populateForm(expense: ExpenseListItem | null | undefined) {
    resetForm();

    if (!expense) {
        return;
    }

    form.amount = String(expense.amount);
    form.description = expense.description;
}

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

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

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

    form.transform((data) => ({
        ...data,
        amount: parseRupiah(data.amount),
    }));

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

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

            <form @submit.prevent="submit">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="expense-amount" required>Jumlah</FieldLabel>
                            <RupiahInput id="expense-amount" v-model="form.amount" autofocus />
                            <FieldError :errors="form.errors.amount ? [form.errors.amount] : []" />
                        </Field>
                        <Field>
                            <FieldLabel for="expense-description" required>Keterangan</FieldLabel>
                            <Textarea id="expense-description" v-model="form.description"
                                placeholder="Contoh: Pembelian perlengkapan toko" rows="3" />
                            <FieldError :errors="form.errors.description ? [form.errors.description] : []" />
                        </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>
