<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { Banknote, SlidersHorizontal } 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 { PayrollListItem } from '@/types/payroll';

const props = defineProps<{
    payroll: PayrollListItem;
}>();

const emit = defineEmits<{
    adjust: [payroll: PayrollListItem];
}>();

const { can } = useCan();

const payConfirmOpen = ref(false);
const payProcessing = ref(false);

function payPayroll() {
    payProcessing.value = true;

    router.post(`/admin/finance/payroll/${props.payroll.id}/pay`, {}, {
        preserveScroll: true,
        onSuccess: () => {
            payConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal membayar gaji.');
        },
        onFinish: () => {
            payProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <Tooltip v-if="payroll.can_adjust && can('payroll.adjust')">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" @click="emit('adjust', payroll)">
                    <SlidersHorizontal class="size-4" />
                    <span class="sr-only">Sesuaikan</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Sesuaikan Gaji</TooltipContent>
        </Tooltip>

        <Tooltip v-if="payroll.can_pay && can('payroll.pay')">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" @click="payConfirmOpen = true">
                    <Banknote class="size-4" />
                    <span class="sr-only">Bayar</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Bayar Gaji</TooltipContent>
        </Tooltip>
    </div>

    <ConfirmDialog v-if="can('payroll.pay')" v-model:open="payConfirmOpen" title="Bayar gaji?"
        :description="`Gaji ${payroll.total_amount_formatted} untuk ${payroll.employee_name} akan dibayar dari kas.`"
        confirm-label="Bayar" cancel-label="Batal" :loading="payProcessing" @confirm="payPayroll" />
</template>
