import { createContext, useEffect, useState } from "react";
import { toast } from "react-toastify";
import useTableSetting from "@/lib/hooks/useTableSetting";
import { flattenArrayOfObjects } from "@/core/utils/flattenArrayOfObjects";
import AskForKeepData from "@/core/components/NotificationDesign/AskForKeepData";

export const DataTableContext = createContext();

const DataTableProvider = ({ children, user_id, page_name, table_name, columns }) => {
    const { settingStore } = useTableSetting();
    const [isInitStates, setInitStates] = useState(false);
    const flatColumns = flattenArrayOfObjects(columns, "columns");
    const [initFilter, setInitFilter] = useState({});
    const [initSort, setInitSort] = useState([]);
    const [filterData, setFilterData] = useState({});
    const [sortData, setSortData] = useState([]);

    useEffect(() => {
        if (!settingStore) return;
        const values = flatColumns.reduce((acc, column) => {
            if (!column.enableColumnFilter) return acc;
            const filter = settingStore?.[user_id]?.[page_name]?.[table_name]?.["filters"]?.find(
                (filter) => filter.id === column.id
            );
            if (column.datatype === "array") {
                acc[column.id] = {
                    id: column.id,
                    value: filter?.value || [],
                    filterFn: filter?.filterFn || column._filterFn,
                    datatype: column.datatype,
                };
            } else if (column._filterFn === "between") {
                acc[column.id] = {
                    id: column.id,
                    value: filter?.value || ["", ""],
                    filterFn: filter?.filterFn || column._filterFn,
                    datatype: column.datatype,
                };
            } else {
                acc[column.id] = {
                    id: column.id,
                    value: filter?.value || "",
                    filterFn: filter?.filterFn || column._filterFn,
                    datatype: column.datatype,
                };
            }
            return acc;
        }, {});
        setFilterData(values);
        setSortData(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || []);
        setInitFilter(values);
        setInitSort(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || []);
        setInitStates(true);
    }, [settingStore, isInitStates]);

    useEffect(() => {
        if (
            JSON.stringify(initFilter) !== JSON.stringify(filterData) ||
            JSON.stringify(initSort) !== JSON.stringify(sortData)
        ) {
            if (!toast.isActive("keep_data", "filtering")) {
                toast(
                    <AskForKeepData
                        filterData={filterData}
                        sortData={sortData}
                        user_id={user_id}
                        page_name={page_name}
                        table_name={table_name}
                        columns={flatColumns}
                    />,
                    {
                        containerId: "filtering",
                        toastId: "keep_data",
                        className: "filter-toast",
                        position: "bottom-left",
                        draggable: true,
                        autoClose: false,
                    }
                );
            } else {
                toast.update("keep_data", {
                    containerId: "filtering",
                    toastId: "keep_data",
                    render: (
                        <AskForKeepData
                            filterData={filterData}
                            sortData={sortData}
                            user_id={user_id}
                            page_name={page_name}
                            table_name={table_name}
                            columns={flatColumns}
                        />
                    ),
                });
            }
        } else {
            toast.dismiss({ containerId: "datatable" });
        }
    }, [filterData, sortData]);

    if (!isInitStates) return null;

    return (
        <DataTableContext.Provider value={{ filterData, setFilterData, sortData, setSortData }}>
            {children}
        </DataTableContext.Provider>
    );
};

export default DataTableProvider;
