import { Portal } from "@/lib/portal/components";
import { FC, PropsWithChildren, use, useEffect, useState } from "react";
import { DevToolboxContext } from "./context";
import { WrenchScrewdriverIcon } from "@heroicons/react/24/solid";
import { XMarkIcon } from "@heroicons/react/16/solid";

export const DevToolbox: FC = () => {
  const { tools, shouldShowDevTools } = use(DevToolboxContext);
  const [open, setOpen] = useState(false);
  return shouldShowDevTools
    ? (
      <Portal>
        <div className="dev-portal flex flex-col gap-2 fixed bottom-2 right-2 border rounded-lg bg-black/50">
          {open
            ? (
              <div className="relative p-2">
                <button
                  className="p-1 absolute top-2 right-2"
                  onClick={() => setOpen(!open)}
                >
                  <XMarkIcon className="w-3 h-3">
                  </XMarkIcon>
                </button>
                <p className="mb-4 mr-8">Dev Toolbox</p>
                {Object.values(tools)}
              </div>
            )
            : (
              <div>
                <button className="p-4" onClick={() => setOpen(!open)}>
                  <WrenchScrewdriverIcon className="w-4 h-4">
                  </WrenchScrewdriverIcon>
                </button>
              </div>
            )}
        </div>
      </Portal>
    )
    : <></>;
};

export const DevTool: FC<PropsWithChildren<{ id: string }>> = (
  { children, id },
) => {
  const { addTool, removeTool } = use(DevToolboxContext);
  useEffect(() => {
    addTool(id, children);
    (() => removeTool(id));
  }, [addTool, children, id, removeTool]);

  return <></>;
};
