<script setup lang="ts">
import { Pencil, Trash2 } from '@lucide/vue';
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 { useDestroy } from '@/composables/useDestroy';
import type { ExpenseListItem } from '@/types/expense';

import { destroy } from '@/routes/admin/finance/expenses';

const props = defineProps<{
    expense: ExpenseListItem;
}>();

const emit = defineEmits<{
    edit: [expense: ExpenseListItem];
}>();

const { can } = useCan();

const { open: deleteConfirmOpen, processing: deleteProcessing, destroy: destroyExpense } = useDestroy({
    url: destroy.url(props.expense.id),
    onError: (errors) => errors.amount || errors.transaction || 'Gagal menghapus pengeluaran.',
});
</script>

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

        <Tooltip v-if="can('expenses.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('expenses.delete')" v-model:open="deleteConfirmOpen" title="Hapus pengeluaran?"
        :description="`Pengeluaran ${expense.amount_formatted} akan dihapus. Saldo kas akan disesuaikan.`"
        confirm-label="Hapus" cancel-label="Batal" destructive :loading="deleteProcessing" @confirm="destroyExpense" />
</template>
