"use client";

import {
  createContext,
  Dispatch,
  FC,
  PropsWithChildren,
  ReactNode,
  SetStateAction,
  useCallback,
  useEffect,
  useState,
} from "react";
import { DevToolbox } from "./Toolbox";

interface ContextProps {
  tools: Record<string, ReactNode>;
  addTool: (key: string, r: ReactNode) => void;
  removeTool: (key: string) => void;
  shouldShowDevTools: boolean;
  setShouldShowDevTools: Dispatch<SetStateAction<boolean>>;
}

export const DevToolboxContext = createContext<ContextProps>({
  tools: {},
  addTool: () => {},
  removeTool: () => {},
  shouldShowDevTools: false,
  setShouldShowDevTools: () => {},
});

export const DevToolboxContextProvider: FC<
  PropsWithChildren<{ isDev: boolean }>
> = (
  { children, isDev },
) => {
  const [tools, setTools] = useState<Record<string, ReactNode>>({});
  const [shouldShowDevTools, setShouldShowDevTools] = useState(isDev);

  const addTool = useCallback((key: string, r: ReactNode) => {
    setTools((t) => ({ ...t, [key]: r }));
  }, []);
  const removeTool = useCallback((key: string) => {
    setTools((t) => ({ ...t, [key]: undefined }));
  }, []);

  useEffect(() => {
    if (localStorage.getItem("dev")) setShouldShowDevTools(true);
  }, []);

  return (
    <DevToolboxContext.Provider
      value={{
        tools,
        addTool,
        removeTool,
        shouldShowDevTools,
        setShouldShowDevTools,
      }}
    >
      {children}
      <DevToolbox></DevToolbox>
    </DevToolboxContext.Provider>
  );
};
