<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
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 { CuttingStatus } from '@/constants/cutting-status';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { transition_status } from '@/routes/admin/manage/cuttings';

const props = defineProps<{
    cuttingId: number;
}>();

const open = defineModel<boolean>('open', { required: true });

const rejectForm = useForm({
    status: CuttingStatus.REJECTED,
    reason: '',
});

watch(open, (isOpen) => {
    if (!isOpen) {
        rejectForm.reset();
        rejectForm.clearErrors();
    }
});

function submitReject() {
    rejectForm.post(transition_status.url(props.cuttingId), {
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: (errors: Record<string, string>) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    });
}
</script>

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

            <form @submit.prevent="submitReject">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="cutting-reject-reason" required>Alasan Penolakan</FieldLabel>
                            <Textarea id="cutting-reject-reason" v-model="rejectForm.reason"
                                placeholder="Masukkan alasan penolakan" rows="3" autofocus
                                :maxlength="FIELD_LIMITS.reason" />
                            <FieldError :errors="rejectForm.errors.reason
                                ? [rejectForm.errors.reason]
                                : []
                                " />
                        </Field>
                    </FieldSet>
                </FieldGroup>

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