<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { 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 { Textarea } from '@/components/ui/textarea';
import { formErrors } from '@/lib/form';
import type { LeaveRequestListItem } from '@/types/leave-request';

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

const props = defineProps<{
    leaveRequest?: LeaveRequestListItem | null;
}>();

const form = useForm({
    reason: '',
});

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

watch(open, (isOpen) => {
    if (!isOpen) {
        resetForm();
    }
});

function submit() {
    if (!props.leaveRequest) {
        return;
    }

    form.post(`/admin/hr/leave-requests/${props.leaveRequest.id}/reject`, {
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: () => {
            toast.error('Gagal menolak pengajuan cuti. Periksa kembali formulir.');
        },
    });
}
</script>

<template>
    <Dialog v-model:open="open">
        <DialogContent class="sm:max-w-md">
            <DialogHeader>
                <DialogTitle>Tolak Pengajuan Cuti</DialogTitle>
            </DialogHeader>

            <form @submit.prevent="submit">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="reject-reason" required>Alasan Penolakan</FieldLabel>
                            <Textarea id="reject-reason" v-model="form.reason" placeholder="Tuliskan alasan penolakan"
                                rows="3" autofocus />
                            <FieldError :errors="formErrors(form, 'reason')" />
                        </Field>
                    </FieldSet>
                </FieldGroup>

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