import React, { createContext, FC, useContext, useEffect, useState } from "react";
import { useProjectsContext } from "../../contexts/ProjectsContext.tsx";
import { MODULES } from "../modules.tsx";
import { Module } from "../types.tsx";

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

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

const useModulesContextState = () => {
    const { selectedProject } = useProjectsContext();

    const [modules, setModules] = useState<Module[]>([]);

    useEffect(() => {
        const modules = selectedProject?.modules ?? [];
        const projectModules = modules.map(module => {
            return MODULES[module.key];
        }) ?? [];
        setModules(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;
};
