import { Head, router } from '@inertiajs/react';
import { useCallback, useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { PaginationState, SortState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { index as payrollPeriodsIndex } from '@/routes/admin/finance/payroll-periods';
import { show as payrollPeriodShow } from '@/routes/admin/finance/payroll-periods';
import { 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;
    };
};

const MONTH_NAMES = [
    '', 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
    'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember',
];

export default function PayrollPeriodIndex({ payrollPeriods }: Props) {
    const [closing, setClosing] = useState<PayrollPeriod | null>(null);
    const [reopening, setReopening] = useState<PayrollPeriod | null>(null);
    const [search, setSearch] = useState('');
    const [sort, setSort] = useState<SortState>({ column: 'created_at', direction: 'desc' });

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

    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),
        });
    }

    function handlePageChange(page: number) {
        router.get(payrollPeriodsIndex(), {
            page,
            per_page: pagination.per_page,
            search,
            sort: sort.column,
            direction: sort.direction,
        }, { preserveState: true, replace: true });
    }

    function handlePerPageChange(perPage: number) {
        router.get(payrollPeriodsIndex(), {
            page: 1,
            per_page: perPage,
            search,
            sort: sort.column,
            direction: sort.direction,
        }, { preserveState: true, replace: true });
    }

    const handleSearchChange = useCallback((value: string) => {
        setSearch(value);
        router.get(payrollPeriodsIndex(), {
            page: 1,
            per_page: pagination.per_page,
            search: value,
            sort: sort.column,
            direction: sort.direction,
        }, { preserveState: true, replace: true });
    }, [pagination.per_page, sort]);

    function handleSortChange(column: string, direction: 'asc' | 'desc') {
        setSort({ column, direction });
        router.get(payrollPeriodsIndex(), {
            page: 1,
            per_page: pagination.per_page,
            search,
            sort: column,
            direction,
        }, { preserveState: true, replace: true });
    }

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

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Gaji
                        </h2>
                    </div>
                </div>

                <DataTable
                    columns={columns}
                    data={payrollPeriods.data}
                    searchKey="year"
                    searchPlaceholder="Cari periode..."
                    emptyText="Belum ada periode gaji."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    onSortChange={handleSortChange}
                    currentSort={sort}
                    searchValue={search}
                />

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

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

PayrollPeriodIndex.layout = {
    breadcrumbs: [
        {
            title: 'Keuangan',
            href: payrollPeriodsIndex(),
        },
        {
            title: 'Gaji',
            href: payrollPeriodsIndex(),
        },
    ],
};
