<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { 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 { AttendanceListItem } from '@/types/attendance';
import { destroy } from '@/routes/admin/hr/attendances';

const props = defineProps<{
    attendance: AttendanceListItem;
}>();

const { can } = useCan();

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

function destroyAttendance() {
    deleteProcessing.value = true;

    router.delete(destroy.url(props.attendance.id), {
        preserveScroll: true,
        onSuccess: () => {
            deleteConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menghapus data presensi.');
        },
        onFinish: () => {
            deleteProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <Tooltip v-if="can('attendances.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('attendances.delete')"
        v-model:open="deleteConfirmOpen"
        title="Hapus data presensi?"
        :description="`Presensi tanggal ${attendance.attendance_date_formatted} akan dihapus secara permanen.`"
        confirm-label="Hapus"
        cancel-label="Batal"
        destructive
        :loading="deleteProcessing"
        @confirm="destroyAttendance"
    />
</template>
