<script setup lang="ts">
import { Head, router } from '@inertiajs/vue3';
import { Banknote, Lock } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import { createColumns } from '@/components/admin/finance/payroll/columns';
import PayrollAdjustmentModal from '@/components/admin/finance/payroll/PayrollAdjustmentModal.vue';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { DataTable } from '@/components/data-table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/composables/useCan';
import { useDataTableQuery, useDataTableQuerySync } from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableSort } from '@/types/data-table';
import type { PayrollListItem, PayrollPageProps } from '@/types/payroll';

const props = defineProps<PayrollPageProps>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');
const selectedPeriodId = ref(props.filters.period_id ? String(props.filters.period_id) : '');
const adjustmentModalOpen = ref(false);
const adjustingPayroll = ref<PayrollListItem | null>(null);
const closeConfirmOpen = ref(false);
const closeProcessing = ref(false);

const { query, setSearch, setSort, setFilter, resetFilters, syncFromServer } = useDataTableQuery({
    url: '/admin/finance/payroll',
    initial: { ...props.filters, period_id: props.filters.period_id ? String(props.filters.period_id) : '' },
    filterKeys: ['period_id'],
});

useDataTableQuerySync(() => props.filters, syncFromServer);

const columns = computed(() => createColumns(openAdjustModal));

const currentSort = computed<DataTableSort | null>(() => {
    if (!query.value.sort || !query.value.direction) {
        return null;
    }

    return {
        column: query.value.sort,
        direction: query.value.direction,
    };
});

const pagination = computed(() => {
    if (!props.payrolls) {
        return null;
    }

    return {
        currentPage: props.payrolls.current_page,
        perPage: props.payrolls.per_page,
        lastPage: props.payrolls.last_page,
        total: props.payrolls.total,
    };
});

const canClosePeriod = computed(() => (
    props.currentPeriod?.status === 'open'
    && can('payroll.close')
));

function openAdjustModal(payroll: PayrollListItem) {
    adjustingPayroll.value = payroll;
    adjustmentModalOpen.value = true;
}

function closePeriod() {
    if (!props.currentPeriod) {
        return;
    }

    closeProcessing.value = true;

    router.post(`/admin/finance/payroll/periods/${props.currentPeriod.id}/close`, {}, {
        preserveScroll: true,
        onSuccess: () => {
            closeConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menutup periode gaji.');
        },
        onFinish: () => {
            closeProcessing.value = false;
        },
    });
}

watch(search, (value) => {
    setSearch(value);
});

watch(selectedPeriodId, (value) => {
    setFilter('period_id', value);
});

watch(
    () => props.filters.search,
    (value) => {
        search.value = value ?? '';
    },
);

watch(
    () => props.filters.period_id,
    (value) => {
        selectedPeriodId.value = value ? String(value) : '';
    },
);
</script>

<template>

    <Head title="Gaji" />

    <AdminLayout>
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div class="space-y-1">
                <h2 class="text-2xl font-bold tracking-tight">
                    Gaji
                </h2>
                <p v-if="currentPeriod" class="text-sm text-muted-foreground">
                    Periode {{ currentPeriod.period_label }}
                    <Badge class="ml-2" :variant="currentPeriod.status === 'open' ? 'default' : 'secondary'">
                        {{ currentPeriod.status_label }}
                    </Badge>
                </p>
            </div>

            <div class="flex shrink-0 flex-col gap-2 sm:flex-row sm:items-center">
                <Select v-if="periods.length > 0" v-model="selectedPeriodId">
                    <SelectTrigger class="w-full sm:w-[200px]">
                        <SelectValue placeholder="Pilih periode" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem v-for="period in periods" :key="period.id" :value="String(period.id)">
                            {{ period.period_label }}
                        </SelectItem>
                    </SelectContent>
                </Select>

                <Button v-if="canClosePeriod" variant="outline" class="shrink-0" @click="closeConfirmOpen = true">
                    <Lock class="size-4" />
                    Tutup Periode
                </Button>
            </div>
        </div>

        <div v-if="summary" class="grid gap-4 md:grid-cols-2">
            <Card>
                <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle class="text-sm font-medium text-muted-foreground">
                        Total Belum Dibayar
                    </CardTitle>
                    <Banknote class="size-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                    <div class="text-3xl font-bold tracking-tight">
                        {{ summary.total_net_amount_formatted }}
                    </div>
                    <p class="mt-1 text-sm text-muted-foreground">
                        {{ summary.unpaid_count }} slip belum dibayar
                    </p>
                </CardContent>
            </Card>

            <Card>
                <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle class="text-sm font-medium text-muted-foreground">
                        Sudah Dibayar
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <div class="text-3xl font-bold tracking-tight">
                        {{ summary.paid_count }}
                    </div>
                    <p class="mt-1 text-sm text-muted-foreground">
                        slip gaji lunas
                    </p>
                </CardContent>
            </Card>
        </div>

        <Card v-if="payrolls && pagination" class="min-w-0">
            <CardContent class="min-w-0 pt-6">
                <DataTable v-model:search="search" :columns="columns" :data="payrolls.data"
                    :pagination="pagination" :pagination-links="payrolls.links" :sort="currentSort"
                    @sort-change="setSort" @filters-reset="resetFilters" />
            </CardContent>
        </Card>

        <Card v-else>
            <CardContent class="py-12 text-center text-muted-foreground">
                Belum ada periode gaji. Periode akan dibuat otomatis setiap awal bulan.
            </CardContent>
        </Card>

        <PayrollAdjustmentModal v-if="can('payroll.adjust')" v-model:open="adjustmentModalOpen"
            :payroll="adjustingPayroll" :adjustment-types="adjustmentTypes" />

        <ConfirmDialog v-if="canClosePeriod" v-model:open="closeConfirmOpen" title="Tutup periode gaji?"
            description="Pastikan semua gaji sudah dibayar sebelum menutup periode."
            confirm-label="Tutup Periode" cancel-label="Batal" :loading="closeProcessing" @confirm="closePeriod" />
    </AdminLayout>
</template>
