<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { computed, ref } from 'vue';
import { toast } from 'vue-sonner';
import { RowApproveAction, RowDeleteAction, RowEditAction, RowRejectAction } from '@/components/button';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { useCan } from '@/composables/useCan';
import type { LeaveRequestListItem } from '@/types/leave-request';
import { destroy, approve } from '@/routes/admin/hr/leave_requests';

const props = defineProps<{
    leaveRequest: LeaveRequestListItem;
    authEmployeeId: number | null;
}>();

const emit = defineEmits<{
    edit: [leaveRequest: LeaveRequestListItem];
    reject: [leaveRequest: LeaveRequestListItem];
}>();

const { can } = useCan();

const isOwner = computed(() => (
    props.authEmployeeId !== null
    && props.leaveRequest.employee_id === props.authEmployeeId
));

const canEdit = computed(() => (
    props.leaveRequest.is_editable
    && !can('leave_requests.verify')
    && isOwner.value
    && can('leave_requests.update')
));

const canDelete = computed(() => (
    props.leaveRequest.is_editable
    && !can('leave_requests.verify')
    && isOwner.value
    && can('leave_requests.delete')
));

const approveConfirmOpen = ref(false);
const approveProcessing = ref(false);

function approveLeaveRequest() {
    approveProcessing.value = true;

    router.post(approve.url(props.leaveRequest.id), {}, {
        preserveScroll: true,
        onSuccess: () => {
            approveConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menyetujui pengajuan cuti.');
        },
        onFinish: () => {
            approveProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <RowEditAction v-if="canEdit" @click="emit('edit', leaveRequest)" />

        <RowApproveAction v-if="leaveRequest.can_verify && can('leave_requests.verify')" tooltip="Setujui"
            @click="approveConfirmOpen = true" />

        <RowRejectAction v-if="leaveRequest.can_verify && can('leave_requests.verify')" tooltip="Tolak"
            @click="emit('reject', leaveRequest)" />

        <template v-if="canDelete">
            <RowDeleteAction :action-url="destroy.url(leaveRequest.id)" title="Hapus pengajuan cuti?"
                :description="`Pengajuan cuti ${leaveRequest.employee_name} akan dihapus.`"
                error-message="Gagal menghapus pengajuan cuti." />
        </template>
    </div>

    <ConfirmDialog v-if="can('leave_requests.verify')" v-model:open="approveConfirmOpen" title="Setujui cuti?"
        :description="`Cuti ${leaveRequest.employee_name} (${leaveRequest.start_date_formatted} - ${leaveRequest.end_date_formatted}, ${leaveRequest.total_days} hari) akan disetujui.`"
        confirm-label="Setujui" cancel-label="Batal" :loading="approveProcessing" @confirm="approveLeaveRequest" />
</template>
