import { createContext, useCallback, useEffect, useReducer } from "react";
import useRequest from "@/lib/app/hooks/useRequest";
import { GET_CATEGORY } from "@/core/data/apiRoutes";

const reducer = (state, action) => {
    switch (action.type) {
        case "CHANGE_ACTIVE_ID":
            return { ...state, active_id: action.id };
        case "SET_CATEGORIES":
            return { ...state, categoryLists: action.cat };
        case "SET_SUBCATEGORIES":
            return { ...state, subCategoryLists: action.subCat };
        default:
            return state;
    }
};
export const CategoriesContext = createContext();

export const CategoriesProvider = ({ children }) => {
    const requestServer = useRequest({ auth: true, notification: false });
    const [state, dispatch] = useReducer(reducer, {
        categoryLists: [],
        subCategoryLists: [],
        active_id: null,
    });

    useEffect(() => {
        requestServer(GET_CATEGORY, "get")
            .then(({ data }) => {
                const subCat = data.data;
                const cat = subCat.reduce((accumulator, currentValue) => {
                    if (!accumulator.find((item) => item.category_id === currentValue.category_id)) {
                        accumulator.push(currentValue);
                    }
                    return accumulator;
                }, []);
                dispatch({ type: "SET_CATEGORIES", cat });
                dispatch({ type: "SET_SUBCATEGORIES", subCat });
            })
            .catch(() => {});
    }, []);

    const setCategoryID = useCallback((id) => {
        dispatch({ type: "CHANGE_ACTIVE_ID", id });
    });

    return (
        <CategoriesContext.Provider
            value={{
                categoryLists: state.categoryLists,
                subCategoryLists: state.subCategoryLists,
                active_id: state.active_id,
                setCategoryID,
            }}
        >
            {children}
        </CategoriesContext.Provider>
    );
};
