import { GET_CATEGORY } from "@/core/utils/routes";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useReducer,
} from "react";
import useRequest from "../hooks/useRequest";

const initialState = {
  categoryLists: [],
  subCategoryLists: [],
  active_category_id: null,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "SET_CATEGORIES":
      return { ...state, categoryLists: action.payload };
    case "SET_SUBCATEGORIES":
      return { ...state, subCategoryLists: action.payload };
    default:
      return state;
  }
};

export const CategoriesContext = createContext(null);

export const CategoriesProvider = ({ children }) => {
  const requestServer = useRequest({ notificationShow: false });

  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const { data } = await requestServer(GET_CATEGORY, "get");
        const subCategories = data.data;

        const categories = Array.from(
          new Map(
            subCategories.map((item) => [item.category_id, item]),
          ).values(),
        );

        dispatch({ type: "SET_CATEGORIES", payload: categories });
        dispatch({ type: "SET_SUBCATEGORIES", payload: subCategories });
      } catch (error) {}
    };

    fetchCategories();
  }, []);

  const contextValue = useMemo(
    () => ({
      categoryLists: state.categoryLists,
      subCategoryLists: state.subCategoryLists,
      active_category_id: state.active_category_id,
    }),
    [state],
  );

  return (
    <CategoriesContext.Provider value={contextValue}>
      {children}
    </CategoriesContext.Provider>
  );
};

export const useCategory = () => useContext(CategoriesContext);
