import DataTable_Paper from "./table/Paper";
import {useMaterialReactTable} from "material-react-table";
import {FA_DATATABLE_LOCALIZATION} from "./localization/fa/datatable";
import useTableSetting from "@/lib/hooks/useTableSetting";
import {flattenArrayOfObjects} from "@/core/utils/flattenArrayOfObjects";
import Toolbar from "@/components/home/Toolbar";
import useDataTable from "@/lib/hooks/useDataTable";
import {useMemo, useState} from "react";

const data = [
    {
        name: {
            firstName: 'امین',
            lastName: 'قاسمپور',
        },
        address: 'فلان جا',
        city: 'تهران',
        state: 'بررسی شده',
        price: '20',
        updated_at: '2024/05/02',
        company: 'همراه اول',
        area: 'منطقه 5',
    },
    {
        name: {
            firstName: 'امیر حسین',
            lastName: 'محمودی',
        },
        address: 'فلان جا',
        city: 'تهران',
        state: 'تکمیل شده',
        price: '27',
        updated_at: '2024/05/02',
        company: 'وایتل',
        area: 'منطقه 27',
    },
    {
        name: {
            firstName: 'یاسمن',
            lastName: 'علی اکبری',
        },
        address: 'فلان جا',
        city: 'شیراز',
        state: 'بررسی شده',
        price: '32',
        updated_at: '2024/05/02',
        company: 'ایرانسل',
        area: 'منطقه 23',
    },
    {
        name: {
            firstName: 'حمیدرضا',
            lastName: 'رنجبرپور',
        },
        address: 'فلان جا',
        city: 'اصفهان',
        state: 'بررسی شده',
        price: '45',
        updated_at: '2024/05/02',
        company: 'ایرانول',
        area: 'منطقه 21',
    },
    {
        name: {
            firstName: 'محمد',
            lastName: 'جلالی',
        },
        address: 'فلان جا',
        city: 'رشت',
        state: 'درحال بررسی',
        price: '8',
        updated_at: '2024/05/02',
        company: 'فیلیمو',
        area: 'منطقه 8',
    },
];

const DataTable_Main = (props) => {
    const {filterData} = useDataTable();
    const {table_url, user_id, page_name, table_name, columns, initialStateProps} = props
    const flatColumns = flattenArrayOfObjects(columns, 'columns')
    const {settingStore, hideAction, sortAction} = useTableSetting();
    const [pagination, setPagination] = useState({pageIndex: 0, pageSize: 10});
    const filters = Object.keys(filterData)
        .map(key => {
            const value = filterData[key].value;
            if (value !== "" &&
                !(Array.isArray(value) && (value.length === 0 || (value.length === 2 && value[0] === "" && value[1] === "")))) {
                return filterData[key];
            }
        })
        .filter(Boolean);
    const storedFilters = settingStore?.[user_id]?.[page_name]?.[table_name]?.filters;
    const finalFilters = storedFilters || filters;

    const fetchUrl = useMemo(() => {
        const params = new URLSearchParams();
        params.set("start", `${pagination.pageIndex * pagination.pageSize}`);
        params.set("size", pagination.pageSize);
        params.set("filters", JSON.stringify(finalFilters ?? []));
        params.set("sorting", JSON.stringify(settingStore?.[user_id]?.[page_name]?.[table_name]?.['sorts'] ?? []));
        return `${table_url}?${params}`;
    }, [table_url, finalFilters, pagination, columns]);

    const onColumnVisibilityChange = (event) => {
        const settingValue = event();
        hideAction(user_id, page_name, table_name, settingValue, flatColumns);
    };
    const onSortingChange = (event) => {
        const settingValue = event(settingStore?.[user_id]?.[page_name]?.[table_name]?.['sorts'] || []);
        sortAction(user_id, page_name, table_name, settingValue, flatColumns);
    }

    const table = useMaterialReactTable({
        localization: FA_DATATABLE_LOCALIZATION,
        columns,
        data: data,
        // manualSorting: true,
        renderTopToolbarCustomActions: ({table}) => (<>
            <Toolbar
                columns={flatColumns}
            />
        </>),
        initialState: {
            density: 'compact',
            columnVisibility: settingStore?.[user_id]?.[page_name]?.[table_name]?.['hides'],
            sorting: settingStore?.[user_id]?.[page_name]?.[table_name]?.['sorts'] || [],
            ...initialStateProps
        },
        state: {
            columnVisibility: settingStore?.[user_id]?.[page_name]?.[table_name]?.['hides'],
            sorting: settingStore?.[user_id]?.[page_name]?.[table_name]?.['sorts'] || [],
            pagination
        },
        muiTableHeadProps: {
            sx: {
                borderTop: "1px solid #e1e1e1",
                borderBottom: "2px solid #e1e1e1",
            }
        },
        muiTableHeadCellProps: {
            sx: {
                color: "primary.main",
                borderLeft: "1px solid #e1e1e1",
                "&:first-of-type": {
                    borderLeft: "unset"
                }
            },
        },
        muiTableBodyCellProps: {
            sx: {
                borderLeft: "1px solid #e1e1e1",
                "&:first-of-type": {
                    borderLeft: "unset"
                }
            },
        },
        manualFiltering: true,
        manualPagination: true,
        onPaginationChange: setPagination,
        manualSorting: true,
        onColumnVisibilityChange: onColumnVisibilityChange,
        onSortingChange: onSortingChange,
        ...props
    })

    return <DataTable_Paper table={table} columns={flatColumns} user_id={user_id} page_name={page_name}
                            table_name={table_name}/>;
};

export default DataTable_Main;



