<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 { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import { reject } from '@/routes/admin/hr/leave_requests';
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(reject.url(props.leaveRequest.id), {
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    });
}
</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="Contoh: Kuota cuti untuk bulan ini sudah habis" rows="3" autofocus
                                :maxlength="FIELD_LIMITS.reason" />
                            <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>
