import { flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import { ArrowDown2, ArrowLeft2, ArrowRight2, ArrowUp2, SearchNormal1 } from "iconsax-react"
import { FC, useEffect, useState } from "react"
import { Input } from "./input"
import { ComboBox } from "./combo-box"
import { Loading } from "./loading"
import { tableRows } from "../../utility/table-rows"
import { useParamsStore } from "../../store/params"

type Props = {
    columns: any
    data: any
    tableStatus?: boolean,
    isLoading?: boolean,
    totalData?: number,
    tableScore?: number
}

type ADSortType = {
    key: string,
    value: 1 | -1
}

export const Table: FC<Props> = ({ columns, data, tableStatus = false, tableScore = 0, isLoading = false, totalData = 0 }) => {
    const [aDSort, setADSort] = useState<ADSortType>({
        key: "",
        value: -1
    })
    const { updateParams, params, clearParams } = useParamsStore()
    const totalPages = Math.ceil(totalData / params?.rows)
    const table = useReactTable({
        data: data ? data : [],
        columns: columns ? columns : [],
        getCoreRowModel: getCoreRowModel(),
        enableColumnResizing: true,
        columnResizeMode: 'onChange',
        pageCount: params?.rows,
    })

    const handleInputValue = (value: string) => {
        updateParams({
            search: value
        })
    }

    useEffect(() => {
        const newParams: any = {
            page: params?.page,
            rows: params?.rows,
            search: params?.search,
        };
        clearParams(newParams)
        if (aDSort?.key?.length > 0) {
            newParams[aDSort.key] = aDSort.value;
        }
        updateParams(newParams);
    }, [aDSort])

    useEffect(() => {
        updateParams({
            page: 1,
            rows: 10,
            search: ""
        })
    }, [updateParams])

    return (
        <div className="flex flex-col gap-10">
            <div className="flex flex-col sm:flex-row justify-between items-center gap-2.5 md:gap-10">
                <div className="sm:max-w-[300px] xl:max-w-[450px] w-full">
                    <Input placeholder="جستجو" value={params?.search} onChange={(e: any) => {
                        handleInputValue(e?.target?.value)
                    }} className="bg-auth-form placeholder:text-[#777577]" icon={<SearchNormal1 color="#777577" />} />
                </div>
                <div className="w-full sm:max-w-[100px]">
                    <ComboBox placeholder={params?.rows.toString()} className="bg-auth-form" data={tableRows} mode="table" />
                </div>
            </div>
            <div className="w-full flex justify-start items-end text-sm lg:text-lg text-primary-text-color font-normal -mb-7 pl-2">{tableStatus && `امتیاز من : ${tableScore}`}</div>
            <div className="block max-w-full min-h-max overflow-x-auto overflow-y-hidden bg-auth-form rounded-[40px] shadow-sm p-4 pb-0 xl:p-9 xl:pb-0 relative">
                <table>
                    <thead className="border-b border-b-secondary-color">
                        {table.getHeaderGroups().map((headerGroup: any, index: number) => (
                            <tr key={index}>
                                {headerGroup.headers.map((header: any, index: number) => (
                                    <th key={index} onClick={() => {
                                        setADSort({
                                            key: header.getContext()?.column?.id,
                                            value: aDSort?.value === 1 ? -1 : 1
                                        })
                                    }}>
                                        <div {...{ className: header.column.getCanSort() ? "text-secondary-text-color text-base font-normal flex flex-row items-center justify-center gap-1 px-4 py-2" : "", onClick: header.column.getToggleSortingHandler() }}>
                                            {flexRender(header.column.columnDef.header, header.getContext())}
                                            {aDSort?.value === 1 && aDSort?.key === header.getContext()?.column?.id ? <ArrowDown2 color="#777577" className="size-4" /> : <ArrowUp2 color="#777577" className="size-4" />}
                                        </div>
                                    </th>
                                ))}
                            </tr>
                        ))}
                    </thead>
                    {!isLoading && <tbody>
                        {table.getRowModel().rows.map((row: any, index: number) => (
                            <tr key={index}>
                                {row.getVisibleCells().map((cell: any, index: number) => (
                                    <td key={index} className="text-primary-text-color font-normal text-base px-4 py-5 text-center">
                                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                                    </td>
                                ))}
                            </tr>
                        ))}
                    </tbody>}
                </table>
                {isLoading ? <Loading /> :
                    <div className="flex flex-row justify-center items-center border-t p-4 gap-x-3 mt-3">
                        <ArrowRight2 color="#11212D" size={19} className="cursor-pointer" onClick={() => params?.page < totalPages && updateParams({
                            page: params?.page + 1
                        })} />
                        <p className="text-base font-normal text-primary-text-color">{params?.page}-{totalPages}</p>
                        <ArrowLeft2 color="#11212D" size={19} className="cursor-pointer" onClick={() => params?.page > 1 && updateParams({
                            page: params?.page - 1
                        })} />
                    </div>
                }
            </div>
        </div>
    );
}
