
// ReactTableList.tsx
import {
    flexRender,
    getCoreRowModel,
    useReactTable,
    type ColumnDef,
} from "@tanstack/react-table";
import { useState, memo } from "react";

// import IconArrowLeft from "../../assets/icons/icon-arrow-left.svg";
// import IconArrowUp from "../../assets/icons/icon-up.svg";
// import IconArrowDown from "../../assets/icons/icon-arrow-down.svg";
import { on } from "events";
import { useRouter } from "next/navigation";
import InputField from "./Input";
import { useAuthStore } from "@/zustand/auth/useAuthStore";



// Extend ColumnDef to allow isSorting flag
export type CustomColumnDef<T> = ColumnDef<T> & {
    isSorting?: boolean; // New: control sorting per column
};

interface ReactTableListProps<T extends object> {
    columns: CustomColumnDef<T>[];
    data: T[];
    getfilter?: (filter: FilterState) => void;
    isLoading?: boolean;
    isLink?: boolean;
    parentLink?: string;
    keyValue?: keyof T;
    rowclick?: string[];
    customClass?: string;
    onSelectionChange?: (ids: string[]) => void;
    enableSelection?: boolean;
    rowHighlightKey?: keyof T;
    rowHighlightValue?: any;
    searchPlaceHolder?: string;

    // Pagination
    totalPages?: number;
    currentPage?: number;
    onPageChange?: (page: number) => void;
    rowsPerPage?: number;
    onRowsPerPageChange?: (rows: number) => void;
}

export interface FilterState {
    sortOrder: number; // 1 = asc, -1 = desc, 0 = none
    sortKey: string;
}

function ReactTableList<T extends object>({
    columns,
    data,
    getfilter,
    isLoading = false,
    isLink = false,
    parentLink = "/",
    keyValue,
    rowclick,
    customClass = "",
    onSelectionChange,
    enableSelection = false,
    rowHighlightKey,
    rowHighlightValue,
    totalPages = 1,
    currentPage = 1,
    onPageChange,
    rowsPerPage = 10,
    onRowsPerPageChange,
    searchPlaceHolder,
}: ReactTableListProps<T>) {
    const navigate = useRouter();
    const [filter, setFilter] = useState<FilterState>({ sortOrder: 0, sortKey: "" });
    const [selectedIds, setSelectedIds] = useState<string[]>([]);

    const table = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
    });

    const toggleSelect = (id: string) => {
        setSelectedIds((prev) => {
            const newSelected = prev.includes(id)
                ? prev.filter((x) => x !== id)
                : [...prev, id];
            onSelectionChange?.(newSelected);
            return newSelected;
        });
    };

    const getRowBorderClass = (rowData: any): string => {
        if (!rowHighlightKey) return "";
        return rowData[rowHighlightKey as string] === rowHighlightValue ? "isRead" : "";
    };

    const handleSort = (columnId: string, isSortable: boolean) => {
        if (!isSortable) return;

        const newFilter =
            filter.sortKey === columnId
                ? { ...filter, sortOrder: filter.sortOrder === 1 ? -1 : 1 }
                : { sortKey: columnId, sortOrder: 1 };

        setFilter(newFilter);
        getfilter?.(newFilter);
    };

    const { language } = useAuthStore();
    return (
        <div className="w-full">
            <div className="overflow-hidden border border-grey2b rounded-md">
                <div className="p-3 border-b border-grey2b bg-theme-bg flex items-center gap-3">
                    <div className="relative flex-1 max-w-96">
                        <i className="icon icon-search bg-light w-4 h-4 absolute left-2 md:left-4 z-[1] top-1/2 -translate-y-1/2"></i>
                        {/* <InputField /> */}
                        <input type="text" className="w-full border border-grey32 bg-secondary pl-8 md:pl-10 px-4 md:px-5 py-2 md:py-3 text-sm 2xl:text-base font-normal leading-tight outline-none focus:border-light rounded-sm lg:rounded-md" placeholder={searchPlaceHolder ?? "search..."} />
                    </div>
                    <button type="button" title="filter" className="flex items-center md:gap-2 px-3 py-2 text-[0px] md:text-sm text-dark rounded-md border border-grey2b bg-secondary cursor-pointer opacity-80 hover:opacity-100 duration-300 text-light">
                        <i className="icon icon-filter bg-light w-4 h-4"></i>
                        Filter
                    </button>
                </div>
                {/* Table */}
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead>
                            {table.getHeaderGroups().map((headerGroup) => (
                                <tr key={headerGroup.id} className="border-b border-grey2b">
                                    {enableSelection && keyValue && <th>Select</th>}
                                    {headerGroup.headers.map((header) => {
                                        const column = header.column.columnDef as CustomColumnDef<T>;
                                        const isSortable = column.isSorting !== false; // default true

                                        return (
                                            <th
                                                key={header.id}
                                                className={`p-3 text-sm whitespace-nowrap 2xl:text-base font-medium leading-tight bg-secondary cursor-pointer ${language === "en" ? "text-left" : "text-right"} ${!isSortable ? "nofilter" : ""}`}
                                                onClick={() => handleSort(header.id, isSortable)}
                                            >
                                                <span className={`inline-flex items-center relative ${language === "en" ? "pr-4 2xl:pr-5" : "pl-4 2xl:pl-5"}`}>
                                                    {header.isPlaceholder
                                                        ? null
                                                        : flexRender(header.column.columnDef.header, header.getContext())}

                                                    {isSortable && (
                                                        <span className={`sort-body flex! absolute top-1/2 -translate-y-1/2  ${language === "en" ? "right-0" : "left-0"}`}>
                                                            {filter.sortKey === header.id ? (
                                                                filter.sortOrder === 1 ? (
                                                                    <i className="icon icon-chevron-up w-4 h-4 2xl:w-4.5 2xl:h-4.5 bg-light duration-unset! transition-none!"></i>
                                                                    // <svg width="12px" height="12px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                    //     <path d="M12 20V4M12 4L6 10M12 4L18 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                                    // </svg>
                                                                ) : (
                                                                    <i className="icon icon-chevron-up w-4 h-4 2xl:w-4.5 2xl:h-4.5 bg-light rotate-180 duration-unset! transition-none!"></i>
                                                                    // <svg width="12px" height="12px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                    //     <path d="M12 4V20M12 20L18 14M12 20L6 14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                                    // </svg>
                                                                )
                                                            ) : (
                                                                <>
                                                                    {/* <i className="icon icon-chevron-up w-4 h-4 2xl:w-4.5 2xl:h-4.5 bg-light duration-unset! transition-none!"></i>
                                                                    <i className="icon icon-chevron-up w-4 h-4 2xl:w-4.5 2xl:h-4.5 bg-light rotate-180 duration-unset! transition-none!"></i> */}
                                                                </>
                                                            )}
                                                        </span>

                                                    )}
                                                </span>
                                            </th>
                                        );
                                    })}
                                </tr>
                            ))}
                        </thead>

                        <tbody>
                            {isLoading ? (
                                <tr>
                                    <td colSpan={columns.length + (enableSelection ? 1 : 0)} className="py-16 text-center text-sm 2xl:text-base font-medium leading-tight">
                                        <span className="text-gray-500">Loading...</span>
                                    </td>
                                </tr>
                            ) : data.length === 0 ? (
                                <tr>
                                    <td colSpan={columns.length + (enableSelection ? 1 : 0)} className="py-16 text-center text-sm 2xl:text-base font-medium leading-tight">
                                        <span className="text-gray-600 text-lg">No Data Available</span>
                                    </td>
                                </tr>
                            ) : (
                                table.getRowModel().rows.map((row) => {
                                    const rowData = row.original as any;
                                    return (
                                        <tr key={row.id} className={`${getRowBorderClass(rowData)} border-b border-grey2b even:bg-secondary`}>
                                            {enableSelection && keyValue && (
                                                <td>
                                                    {/* <Checkbox ... /> */}
                                                </td>
                                            )}
                                            {row.getVisibleCells().map((cell) => (
                                                <td
                                                    key={cell.id}
                                                    onClick={() => {
                                                        if (isLink && !rowclick?.includes(cell.column.id) && keyValue) {
                                                            navigate.push(`${parentLink}/${rowData[keyValue]}`);
                                                        }
                                                    }}
                                                    className={`p-3 text-sm 2xl:text-base font-regular leading-tight  ${isLink ? "cursor-pointer" : ""}`}
                                                >
                                                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                                                </td>
                                            ))}
                                        </tr>
                                    );
                                })
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Pagination */}
                <div className="flex justify-between items-center flex-wrap gap-2.5 py-2.5 px-3 md:px-4">
                    <div className="flex items-center text-sm leading-tight">
                        <p className="">Row Per Page :</p>
                        <select
                            value={rowsPerPage}
                            className="outline-none cursor-pointer border-b border-secondary"
                            onChange={(e) => { onRowsPerPageChange?.(Number(e.target.value)); onPageChange?.(1); }}
                        >
                            {[10, 15, 20].map((n) => (
                                <option key={n} value={n} className="text-dark!">
                                    {n}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="flex items-stretch gap-2">
                        <button
                            className="w-8 h-8 rounded-sm bg-secondary27 flex items-center justify-center text-sm font-medium leading-none shrink-0 duration-300 ease-in-out cursor-pointer group hover:bg-primary"
                            disabled={currentPage <= 1}
                            onClick={() => onPageChange?.(currentPage - 1)}
                        >
                            <i className={`icon icon-chevron-left w-4.5 h-4.5 bg-light duration-300 ease-in-out group-hover:bg-white ${language === "en" ? "" : "rotate-180"}`}></i>
                        </button>

                        <button
                            className={`w-8 h-8 rounded-sm bg-secondary27 flex items-center justify-center text-sm font-medium leading-none shrink-0 duration-300 ease-in-out cursor-pointer hover:bg-primary hover:text-white ${currentPage === 1 ? "active bg-primary! text-white!" : ""}`}
                            onClick={() => onPageChange?.(1)}
                        >
                            1
                        </button>

                        {currentPage > 4 && <span className="dots">...</span>}

                        {currentPage > 2 && currentPage < totalPages - 1 && (
                            <button className="bg-primary! text-white! active">{currentPage}</button>
                        )}

                        {currentPage < totalPages - 3 && <span className="dots">...</span>}

                        {totalPages > 1 && (
                            <button
                                className={`w-8 h-8 rounded-sm bg-secondary27 flex items-center justify-center text-sm font-medium leading-none shrink-0 duration-300 ease-in-out cursor-pointer hover:bg-primary hover:text-white ${currentPage === totalPages ? "active bg-primary text-white" : ""}`}
                                onClick={() => onPageChange?.(totalPages)}
                            >
                                {totalPages}
                            </button>
                        )}

                        <button
                            className="w-8 h-8 rounded-sm bg-secondary27 flex items-center justify-center text-sm font-medium leading-none shrink-0 duration-300 ease-in-out cursor-pointer group hover:bg-primary"
                            disabled={currentPage >= totalPages}
                            onClick={() => onPageChange?.(currentPage + 1)}
                        >
                            <i className={`icon icon-chevron-left w-4.5 h-4.5 bg-light duration-300 ease-in-out group-hover:bg-white ${language === "en" ? "rotate-180" : ""}`}></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default memo(ReactTableList);