<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { Pencil, Trash2 } from '@lucide/vue';
import { computed, 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 { CashTransactionListItem } from '@/types/cash';

const props = defineProps<{
    transaction: CashTransactionListItem;
}>();

const emit = defineEmits<{
    edit: [transaction: CashTransactionListItem];
}>();

const { can } = useCan();

const showActions = computed(() => props.transaction.reference_type === null);

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

function destroyTransaction() {
    deleteProcessing.value = true;

    router.delete(`/admin/finance/cash/transactions/${props.transaction.id}`, {
        preserveScroll: true,
        onSuccess: () => {
            deleteConfirmOpen.value = false;
        },
        onError: (errors) => {
            toast.error(errors.amount || errors.transaction || 'Gagal menghapus setor kas.');
        },
        onFinish: () => {
            deleteProcessing.value = false;
        },
    });
}
</script>

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

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