import {
    flexRender,
    getCoreRowModel,
    getFilteredRowModel,
    getPaginationRowModel,
    getSortedRowModel,
    createColumnHelper,
    useReactTable,
} from '@tanstack/react-table';
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatAppDateOrDash, formatMoneyAmountOrDash } from '@/lib/dates';

const columnHelper = createColumnHelper();

function SortButton({ column, children }) {
    const sorted = column.getIsSorted();

    return (
        <Button
            type="button"
            variant="ghost"
            size="sm"
            className="-ms-2 h-8 font-medium"
            onClick={column.getToggleSortingHandler()}
        >
            {children}
            {sorted === 'asc' ? (
                <ArrowUp className="ms-1 size-4 opacity-70" />
            ) : sorted === 'desc' ? (
                <ArrowDown className="ms-1 size-4 opacity-70" />
            ) : (
                <ArrowUpDown className="text-muted-foreground ms-1 size-4 opacity-50" />
            )}
        </Button>
    );
}

function paymentMethodLabel(method, labels) {
    if (method === 'bank') {
        return labels.methodBank;
    }

    if (method === 'other') {
        return labels.methodOther;
    }

    return labels.methodCash;
}

export function SarafPaymentsDataTable({ payments, labels, locale = 'en' }) {
    const [sorting, setSorting] = useState([{ id: 'paid_at', desc: true }]);
    const [globalFilter, setGlobalFilter] = useState('');
    const [pagination, setPagination] = useState({
        pageIndex: 0,
        pageSize: 10,
    });

    useEffect(() => {
        setPagination((prev) => ({ ...prev, pageIndex: 0 }));
    }, [globalFilter, sorting]);

    const columns = useMemo(
        () => [
            columnHelper.display({
                id: 'serial',
                header: labels.colSerial,
                cell: ({ row, table }) => {
                    const { pageIndex, pageSize } = table.getState().pagination;
                    return (
                        <span className="text-muted-foreground tabular-nums">
                            {pageIndex * pageSize + row.index + 1}
                        </span>
                    );
                },
                enableSorting: false,
                enableGlobalFilter: false,
            }),
            columnHelper.accessor('paid_at', {
                header: ({ column }) => (
                    <SortButton column={column}>{labels.colDate}</SortButton>
                ),
                cell: (info) => formatAppDateOrDash(info.getValue(), locale),
            }),
            columnHelper.accessor('payment_type', {
                header: labels.colPaymentType,
                cell: (info) =>
                    info.getValue() === 'exchange'
                        ? labels.paymentTypeExchange
                        : labels.paymentTypeGeneral,
                enableSorting: false,
            }),
            columnHelper.accessor('exchange_date', {
                header: labels.colExchangeDate,
                cell: (info) => formatAppDateOrDash(info.getValue(), locale) || '—',
            }),
            columnHelper.accessor('amount', {
                header: ({ column }) => (
                    <div className="flex justify-end">
                        <SortButton column={column} className="me-0">
                            {labels.colAmount}
                        </SortButton>
                    </div>
                ),
                cell: (info) => (
                    <span className="font-medium tabular-nums">
                        {formatMoneyAmountOrDash(info.getValue(), locale)} {labels.usdCurrencyLabel}
                    </span>
                ),
                sortingFn: (rowA, rowB) =>
                    Number(rowA.original.amount) - Number(rowB.original.amount),
            }),
            columnHelper.accessor('payment_method', {
                header: labels.colPaymentMethod,
                cell: (info) => paymentMethodLabel(info.getValue(), labels) || '—',
                enableSorting: false,
            }),
            columnHelper.accessor('reference', {
                header: labels.colReference,
                cell: (info) => info.getValue() || '—',
                enableSorting: false,
            }),
        ],
        [labels, locale],
    );

    // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Table API is not memoization-safe
    const table = useReactTable({
        data: payments,
        columns,
        state: { sorting, globalFilter, pagination },
        onSortingChange: setSorting,
        onGlobalFilterChange: setGlobalFilter,
        onPaginationChange: setPagination,
        getCoreRowModel: getCoreRowModel(),
        getSortedRowModel: getSortedRowModel(),
        getFilteredRowModel: getFilteredRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
        globalFilterFn: (row, _columnId, filterValue) => {
            const q = String(filterValue ?? '').toLowerCase().trim();

            if (!q) {
                return true;
            }

            const reference = String(row.original.reference ?? '').toLowerCase();
            const notes = String(row.original.notes ?? '').toLowerCase();
            const date = String(row.original.paid_at ?? '').toLowerCase();

            return reference.includes(q) || notes.includes(q) || date.includes(q);
        },
    });

    const pageCount = table.getPageCount();
    const pageIndex = table.getState().pagination.pageIndex;
    const pageSize = table.getState().pagination.pageSize;
    const summaryText = labels.paginationSummary
        .replace('{page}', String(pageIndex + 1))
        .replace('{pages}', String(Math.max(pageCount, 1)));

    return (
        <div className="space-y-4">
            <div className="flex max-w-sm flex-col gap-2">
                <Input
                    type="search"
                    value={globalFilter ?? ''}
                    onChange={(e) => setGlobalFilter(e.target.value)}
                    placeholder={labels.searchPlaceholder}
                    className="h-9"
                />
            </div>

            <div className="overflow-x-auto rounded-lg border border-border/80">
                <Table>
                    <TableHeader>
                        {table.getHeaderGroups().map((headerGroup) => (
                            <TableRow key={headerGroup.id} className="bg-muted/40 hover:bg-muted/40">
                                {headerGroup.headers.map((header) => (
                                    <TableHead
                                        key={header.id}
                                        className={
                                            header.column.id === 'amount' ? 'text-end' : undefined
                                        }
                                    >
                                        {header.isPlaceholder
                                            ? null
                                            : flexRender(
                                                  header.column.columnDef.header,
                                                  header.getContext(),
                                              )}
                                    </TableHead>
                                ))}
                            </TableRow>
                        ))}
                    </TableHeader>
                    <TableBody>
                        {table.getRowModel().rows.length === 0 ? (
                            <TableRow>
                                <TableCell
                                    colSpan={columns.length}
                                    className="text-muted-foreground h-24 text-center"
                                >
                                    {labels.emptyPayments}
                                </TableCell>
                            </TableRow>
                        ) : (
                            table.getRowModel().rows.map((row) => (
                                <TableRow key={row.id} className="hover:bg-muted/25">
                                    {row.getVisibleCells().map((cell) => (
                                        <TableCell
                                            key={cell.id}
                                            className={
                                                cell.column.id === 'amount' ? 'text-end' : undefined
                                            }
                                        >
                                            {flexRender(
                                                cell.column.columnDef.cell,
                                                cell.getContext(),
                                            )}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {payments.length > 0 ? (
                <div className="flex flex-col gap-4 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex flex-wrap items-center gap-2">
                        <Label
                            htmlFor="saraf-payments-page-size"
                            className="text-muted-foreground whitespace-nowrap text-sm"
                        >
                            {labels.rowsPerPage}
                        </Label>
                        <select
                            id="saraf-payments-page-size"
                            className="border-input bg-background h-9 rounded-md border px-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
                            value={pageSize}
                            onChange={(e) => {
                                const next = Number(e.target.value);
                                setPagination({ pageIndex: 0, pageSize: next });
                            }}
                        >
                            {[5, 10, 25, 50].map((n) => (
                                <option key={n} value={n}>
                                    {n}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => table.previousPage()}
                            disabled={!table.getCanPreviousPage()}
                        >
                            {labels.paginationPrevious}
                        </Button>
                        <span className="text-muted-foreground min-w-[8rem] text-center text-sm tabular-nums">
                            {summaryText}
                        </span>
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => table.nextPage()}
                            disabled={!table.getCanNextPage()}
                        >
                            {labels.paginationNext}
                        </Button>
                    </div>
                </div>
            ) : null}
        </div>
    );
}
