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 { SalePaymentStatusBadge } from '@/components/sales/sale-payment-status-badge';
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,
    formatPurchaseCurrencyLabel,
} 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 normalizePurchaseRow(row) {
    return {
        ...row,
        sale_number: row.sale_number ?? row.bill_number,
        sold_at: row.sold_at ?? row.purchased_at,
        net_amount: row.net_amount ?? row.total_amount,
    };
}

export function CustomerPurchasesDataTable({
    purchases,
    labels,
    statusLabels,
    locale = 'en',
    showCustomerColumn = false,
    showCurrencyColumn = false,
    onOpenSale,
    searchInputId = 'customer-purchases-search',
    pageSizeInputId = 'customer-purchases-page-size',
}) {
    const [sorting, setSorting] = useState([{ id: 'sold_at', desc: true }]);
    const [globalFilter, setGlobalFilter] = useState('');
    const [pagination, setPagination] = useState({
        pageIndex: 0,
        pageSize: 10,
    });

    const rows = useMemo(
        () => purchases.map((purchase) => normalizePurchaseRow(purchase)),
        [purchases],
    );

    useEffect(() => {
        setPagination((prev) => ({ ...prev, pageIndex: 0 }));
    }, [globalFilter, sorting]);

    const columns = useMemo(() => {
        const cols = [
            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,
            }),
        ];

        if (showCustomerColumn) {
            cols.push(
                columnHelper.accessor('customer_name', {
                    header: ({ column }) => (
                        <SortButton column={column}>{labels.colCustomer}</SortButton>
                    ),
                    cell: (info) => info.getValue() ?? '—',
                }),
            );
        }

        cols.push(
            columnHelper.accessor('sale_number', {
                header: ({ column }) => (
                    <SortButton column={column}>
                        {labels.colSaleNumber ?? labels.colBillNumber}
                    </SortButton>
                ),
                cell: (info) => (
                    <span className="text-primary font-medium underline-offset-4">
                        {info.getValue()}
                    </span>
                ),
            }),
            columnHelper.accessor('sold_at', {
                id: 'sold_at',
                header: ({ column }) => (
                    <SortButton column={column}>
                        {labels.colSoldAt ?? labels.colDate}
                    </SortButton>
                ),
                cell: (info) => formatAppDateOrDash(info.getValue(), locale),
            }),
        );

        if (showCurrencyColumn) {
            cols.push(
                columnHelper.accessor('currency', {
                    header: ({ column }) => (
                        <SortButton column={column}>{labels.colCurrency}</SortButton>
                    ),
                    cell: (info) => formatPurchaseCurrencyLabel(info.getValue(), locale),
                }),
            );
        }

        cols.push(
            columnHelper.accessor('net_amount', {
                header: ({ column }) => (
                    <SortButton column={column}>
                        {labels.colNetAmount ?? labels.colTotal}
                    </SortButton>
                ),
                cell: (info) => (
                    <span className="text-end tabular-nums">
                        {formatMoneyAmountOrDash(info.getValue(), locale)}
                    </span>
                ),
            }),
            columnHelper.accessor('paid_amount', {
                header: ({ column }) => (
                    <SortButton column={column}>{labels.colPaid}</SortButton>
                ),
                cell: (info) => (
                    <span className="text-end tabular-nums">
                        {formatMoneyAmountOrDash(info.getValue(), locale)}
                    </span>
                ),
            }),
            columnHelper.accessor('due_amount', {
                header: ({ column }) => (
                    <SortButton column={column}>{labels.colDue}</SortButton>
                ),
                cell: (info) => (
                    <span className="text-end tabular-nums">
                        {formatMoneyAmountOrDash(info.getValue(), locale)}
                    </span>
                ),
            }),
            columnHelper.accessor('payment_status', {
                header: labels.colStatus,
                cell: (info) => (
                    <SalePaymentStatusBadge
                        status={info.getValue()}
                        labels={statusLabels}
                    />
                ),
                enableSorting: false,
            }),
        );

        return cols;
    }, [labels, locale, showCustomerColumn, showCurrencyColumn, statusLabels]);

    // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Table API is not memoization-safe
    const table = useReactTable({
        data: rows,
        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 r = row.original;
            const statusLabel =
                r.payment_status === 'paid'
                    ? statusLabels.paymentStatusPaid
                    : r.payment_status === 'partial'
                      ? statusLabels.paymentStatusPartial
                      : statusLabels.paymentStatusOpen;

            return [
                r.sale_number,
                r.customer_name,
                r.currency,
                statusLabel,
                formatAppDateOrDash(r.sold_at, locale),
                formatPurchaseCurrencyLabel(r.currency, locale),
            ]
                .filter(Boolean)
                .some((field) => String(field).toLowerCase().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)));

    const emptyLabel = labels.noPurchases ?? labels.noBills;
    const searchPlaceholder =
        labels.purchasesSearchPlaceholder ?? labels.billsSearchPlaceholder;

    return (
        <div className="space-y-4">
            <div className="flex max-w-sm flex-col gap-2">
                <Input
                    id={searchInputId}
                    type="search"
                    value={globalFilter ?? ''}
                    onChange={(e) => setGlobalFilter(e.target.value)}
                    placeholder={searchPlaceholder}
                    className="h-9"
                />
            </div>

            <div className="overflow-x-auto rounded-md border">
                <Table>
                    <TableHeader>
                        {table.getHeaderGroups().map((headerGroup) => (
                            <TableRow key={headerGroup.id}>
                                {headerGroup.headers.map((header) => (
                                    <TableHead
                                        key={header.id}
                                        className={
                                            ['net_amount', 'paid_amount', 'due_amount'].includes(
                                                header.column.id,
                                            )
                                                ? '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"
                                >
                                    {emptyLabel}
                                </TableCell>
                            </TableRow>
                        ) : (
                            table.getRowModel().rows.map((row) => (
                                <TableRow
                                    key={row.id}
                                    className={
                                        onOpenSale
                                            ? 'cursor-pointer hover:bg-muted/40'
                                            : undefined
                                    }
                                    onClick={() => onOpenSale?.(row.original)}
                                >
                                    {row.getVisibleCells().map((cell) => (
                                        <TableCell
                                            key={cell.id}
                                            className="whitespace-normal align-middle"
                                        >
                                            {flexRender(
                                                cell.column.columnDef.cell,
                                                cell.getContext(),
                                            )}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {rows.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={pageSizeInputId}
                            className="text-muted-foreground whitespace-nowrap text-sm"
                        >
                            {labels.rowsPerPage}
                        </Label>
                        <select
                            id={pageSizeInputId}
                            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) => {
                                setPagination({
                                    pageIndex: 0,
                                    pageSize: Number(e.target.value),
                                });
                            }}
                        >
                            {[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>
    );
}
