<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { Trash2 } from '@lucide/vue';
import { ref } from 'vue';
import { toast } from 'vue-sonner';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

const props = defineProps<{
    title?: string;
    description?: string;
    actionUrl?: string; // If provided, handles the deletion request automatically.
    errorMessage?: string;
}>();

const emit = defineEmits<{
    confirm: [];
}>();

const deleteConfirmOpen = ref(false);
const deleteProcessing = ref(false);

function handleConfirm() {
    if (props.actionUrl) {
        deleteProcessing.value = true;
        router.delete(props.actionUrl, {
            preserveScroll: true,
            onSuccess: () => {
                deleteConfirmOpen.value = false;
            },
            onError: (errors) => {
                const firstError = Object.values(errors)[0];
                toast.error(firstError || props.errorMessage || 'Gagal menghapus data.');
            },
            onFinish: () => {
                deleteProcessing.value = false;
            },
        });
    } else {
        emit('confirm');
    }
}
</script>

<template>
    <Tooltip>
        <TooltipTrigger as-child>
            <Button variant="ghost" size="icon" class="text-destructive hover:text-destructive size-8"
                @click="deleteConfirmOpen = true">
                <Trash2 class="size-4" />
                <span class="sr-only">Hapus</span>
            </Button>
        </TooltipTrigger>
        <TooltipContent>Hapus</TooltipContent>
    </Tooltip>

    <ConfirmDialog v-model:open="deleteConfirmOpen" :title="title || 'Hapus data?'"
        :description="description || 'Data akan dihapus secara permanen. Tindakan ini tidak dapat dibatalkan.'"
        confirm-label="Hapus" cancel-label="Batal" destructive :loading="deleteProcessing" @confirm="handleConfirm" />
</template>
