import React, { createContext, FC, useContext, useEffect, useState } from "react";
import { useProjectsContext } from "../../contexts/ProjectsContext.tsx";
import { ModuleNames, MODULES } from "../modules.tsx";
import { Module } from "../types.tsx";
import { RootState } from "../../redux/store.ts";
import { useSelector } from "react-redux";

type ModulesContextState = {
    modules: Module[];
};

const ModulesContext = createContext<ModulesContextState | undefined>(
    undefined,
);

const useModulesContextState = () => {
    const { selectedProject } = useProjectsContext();
    const { isDealsViewer } = useSelector((state: RootState) => state.auth);
    const [modules, setModules] = useState<Module[]>([]);

    const filterModules = (modulesToFilter: Module[]): Module[] => {
        if (isDealsViewer) {
            const modulesForDealsViewer: string[] = [ModuleNames.SERVICES_AND_PRODUCTS];
            return modulesToFilter.filter(module => modulesForDealsViewer.includes(module.info.key));
        }

        return modulesToFilter;
    };

    useEffect(() => {
        const modules = selectedProject?.modules ?? [];
        const projectModules = modules.map(module => {
            return MODULES[module.key];
        }) ?? [];
        setModules(filterModules(projectModules));
    }, [selectedProject?.id]);

    return {
        modules,
    };
};

type CardPageContextProviderProps = {
    children: React.ReactNode;
};

export const ModulesContextProvider: FC<CardPageContextProviderProps> = ({ children }) => {
    const state = useModulesContextState();

    return (
        <ModulesContext.Provider value={state}>
            {children}
        </ModulesContext.Provider>
    );
};

export const useModulesContext = () => {
    const context = useContext(ModulesContext);
    if (!context) {
        throw new Error(
            "useModulesContext must be used within a ModulesContextProvider",
        );
    }
    return context;
};
