<script setup lang="ts">
import { 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 { CustomerListItem } from '@/types/customer';

const props = defineProps<{
    customer: CustomerListItem;
}>();

const emit = defineEmits<{
    edit: [customer: CustomerListItem];
}>();

const { can } = useCan();

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

function destroyCustomer() {
    deleteProcessing.value = true;

    router.delete(`/admin/master/customers/${props.customer.id}`, {
        preserveScroll: true,
        onSuccess: () => {
            deleteConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menghapus customer.');
        },
        onFinish: () => {
            deleteProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <Tooltip v-if="can('customers.update')">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" @click="emit('edit', customer)">
                    <Pencil class="size-4" />
                    <span class="sr-only">Ubah</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Ubah</TooltipContent>
        </Tooltip>

        <Tooltip v-if="can('customers.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('customers.delete')" v-model:open="deleteConfirmOpen" title="Hapus customer?"
        :description="`Customer ${customer.name} akan dihapus secara permanen. Tindakan ini tidak dapat dibatalkan.`"
        confirm-label="Hapus" cancel-label="Batal" destructive :loading="deleteProcessing" @confirm="destroyCustomer" />
</template>
