import { Head, router } from '@inertiajs/react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { PageHeader } from '@/components/page-header';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import { MONTH_NAMES } from '@/lib/constants';
import {
    index as payrollPeriodsIndex,
    show as payrollPeriodShow,
    close,
    reopen,
} from '@/routes/admin/finance/payroll-periods';
import { createPayrollPeriodColumns } from './columns';
import type { PayrollPeriod } from './columns';

type Props = {
    payrollPeriods: {
        data: PayrollPeriod[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

export default function PayrollPeriodIndex({ payrollPeriods }: Props) {
    const { can, hasAnyRole } = useCan();
    const canViewAll = hasAnyRole(['developer', 'owner', 'direktur', 'admin-toko']);
    const [closing, setClosing] = useState<PayrollPeriod | null>(null);
    const [reopening, setReopening] = useState<PayrollPeriod | null>(null);

    const pagination: PaginationState = {
        current_page: payrollPeriods.current_page,
        last_page: payrollPeriods.last_page,
        per_page: payrollPeriods.per_page,
        total: payrollPeriods.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => payrollPeriodsIndex.url(),
        pagination,
    });

    function handleClose() {
        if (!closing) {
            return;
        }

        router.post(
            close(closing.id),
            {},
            {
                onSuccess: () => setClosing(null),
            },
        );
    }

    function handleReopen() {
        if (!reopening) {
            return;
        }

        router.post(
            reopen(reopening.id),
            {},
            {
                onSuccess: () => setReopening(null),
            },
        );
    }

    const columns = createPayrollPeriodColumns({
        showUrl: (id) => payrollPeriodShow(id).url,
        handleClose: (period) => setClosing(period),
        handleReopen: (period) => setReopening(period),
        can,
        canViewAll,
    });

    return (
        <>
            <Head title="Gaji" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader title="Gaji" />

                <DataTable
                    columns={columns}
                    data={payrollPeriods.data}
                    searchKey="year"

                    emptyText="Belum ada periode gaji."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

                <DeleteConfirmDialog
                    target={closing}
                    onOpenChange={(open) => {
                        if (!open) {
                            setClosing(null);
                        }
                    }}
                    title="Tutup Periode Gaji"
                    description={(period) =>
                        `Apakah Anda yakin ingin menutup periode gaji ${MONTH_NAMES[period.month]} ${period.year}? Semua gaji harus sudah dibayar sebelum periode ditutup.`
                    }
                    confirmLabel="Tutup"
                    onConfirm={handleClose}
                />

                <DeleteConfirmDialog
                    target={reopening}
                    onOpenChange={(open) => {
                        if (!open) {
                            setReopening(null);
                        }
                    }}
                    title="Buka Periode Gaji"
                    description={(period) =>
                        `Apakah Anda yakin ingin membuka kembali periode gaji ${MONTH_NAMES[period.month]} ${period.year}?`
                    }
                    confirmLabel="Buka"
                    onConfirm={handleReopen}
                />
            </div>
        </>
    );
}
