<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import { RowApproveAction, RowDeleteAction, RowEditAction, RowPayAction, RowRejectAction } from '@/components/button';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { RupiahInput } from '@/components/form/rupiah-input';
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { useCan } from '@/composables/useCan';
import { parseRupiah } from '@/lib/rupiah';
import { destroy, approve, pay } from '@/routes/admin/finance/employee_advances';
import type { EmployeeAdvanceListItem } from '@/types/employee-advance';

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

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

const { can } = useCan();

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

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

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

const approveConfirmOpen = ref(false);
const payConfirmOpen = ref(false);
const approveProcessing = ref(false);
const payProcessing = ref(false);
const payAmount = ref('');
const payError = ref('');

watch(payConfirmOpen, (open) => {
    if (open) {
        payAmount.value = String(props.employeeAdvance.remaining_amount);
        payError.value = '';
    }
});

function approveEmployeeAdvance() {
    approveProcessing.value = true;

    router.post(approve.url(props.employeeAdvance.id), {}, {
        preserveScroll: true,
        onSuccess: () => {
            approveConfirmOpen.value = false;
        },
        onError: (errors: Record<string, string>) => {
            const message = errors.system ?? Object.values(errors)[0];

            if (message) {
                toast.error(message);
            }
        },
        onFinish: () => {
            approveProcessing.value = false;
        },
    });
}

function payEmployeeAdvance() {
    const amount = Number(parseRupiah(payAmount.value));

    if (!amount || amount <= 0) {
        payError.value = 'Jumlah pembayaran harus lebih dari 0.';

        return;
    }

    if (amount > props.employeeAdvance.remaining_amount) {
        payError.value = 'Jumlah pembayaran melebihi sisa kasbon.';

        return;
    }

    payError.value = '';
    payProcessing.value = true;

    router.post(pay.url(props.employeeAdvance.id), { amount }, {
        preserveScroll: true,
        onSuccess: () => {
            payConfirmOpen.value = false;
        },
        onError: (errors: Record<string, string>) => {
            const message = errors.system ?? Object.values(errors)[0];

            if (message) {
                toast.error(message);
            }
        },
        onFinish: () => {
            payProcessing.value = false;
        },
    });
}
</script>

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

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

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

        <RowPayAction v-if="employeeAdvance.can_pay && can('employee_advances.pay')" tooltip="Bayar Kasbon"
            @click="payConfirmOpen = true" />

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

    <ConfirmDialog v-if="can('employee_advances.verify')" v-model:open="approveConfirmOpen" title="Setujui kasbon?"
        :description="`Kasbon ${employeeAdvance.amount_formatted} untuk ${employeeAdvance.employee_name} akan dicairkan. Saldo kas akan berkurang.`"
        confirm-label="Setujui" cancel-label="Batal" :loading="approveProcessing" @confirm="approveEmployeeAdvance" />

    <ConfirmDialog v-if="can('employee_advances.pay')" v-model:open="payConfirmOpen"
        :title="employeeAdvance.remaining_amount < employeeAdvance.amount ? 'Bayar sisa kasbon?' : 'Bayar kasbon?'"
        :description="`Pembayaran kasbon ${employeeAdvance.employee_name}. Sisa: ${employeeAdvance.remaining_amount_formatted}.`"
        confirm-label="Bayar" cancel-label="Batal" :loading="payProcessing" @confirm="payEmployeeAdvance">
        <template #content>
            <div class="space-y-3 py-2">
                <div class="text-sm text-muted-foreground">
                    <p>Total kasbon: <strong>{{ employeeAdvance.amount_formatted }}</strong></p>
                    <p>Sudah dibayar: <strong>{{ employeeAdvance.paid_amount_formatted }}</strong></p>
                    <p>Sisa: <strong class="text-primary">{{ employeeAdvance.remaining_amount_formatted }}</strong></p>
                </div>
                <Field>
                    <FieldLabel for="pay-amount" required>Jumlah Pembayaran</FieldLabel>
                    <RupiahInput id="pay-amount" v-model="payAmount" placeholder="0" />
                    <FieldError v-if="payError" :errors="[payError]" />
                </Field>

                <div v-if="employeeAdvance.payments && employeeAdvance.payments.length > 0" class="space-y-2">
                    <p class="text-sm font-medium">Riwayat Pembayaran</p>
                    <div class="max-h-40 space-y-2 overflow-y-auto rounded-md border p-2">
                        <div v-for="payment in employeeAdvance.payments" :key="payment.id"
                            class="flex items-center justify-between text-sm">
                            <div>
                                <p class="font-medium">{{ payment.amount_formatted }}</p>
                                <p class="text-xs text-muted-foreground">{{ payment.paid_at_formatted }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </ConfirmDialog>
</template>
