<script setup lang="ts">
import { Link, router } from '@inertiajs/vue3';
import { Pencil, 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';
import { useCan } from '@/composables/useCan';
import type { RawMaterialListItem } from '@/types/raw-material';

const props = defineProps<{
    material: RawMaterialListItem;
}>();

const { can } = useCan();

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

function destroyRawMaterial() {
    deleteProcessing.value = true;

    router.delete(`/admin/master/raw-materials/${props.material.id}`, {
        onSuccess: () => {
            deleteConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menghapus bahan baku.');
        },
        onFinish: () => {
            deleteProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <Tooltip v-if="can('raw-materials.update')">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" as-child>
                    <Link :href="`/admin/master/raw-materials/${material.id}/edit`">
                        <Pencil class="size-4" />
                        <span class="sr-only">Ubah</span>
                    </Link>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Ubah</TooltipContent>
        </Tooltip>

        <Tooltip v-if="can('raw-materials.delete')">
            <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>
    </div>

    <ConfirmDialog v-if="can('raw-materials.delete')" v-model:open="deleteConfirmOpen" title="Hapus bahan baku?"
        :description="`Bahan baku ${material.name} akan dihapus beserta seluruh variannya. Tindakan ini tidak dapat dibatalkan.`"
        confirm-label="Hapus" cancel-label="Batal" destructive :loading="deleteProcessing"
        @confirm="destroyRawMaterial" />
</template>
