import { FolderManager } from "./FolderManager";
import * as Popover from "@radix-ui/react-popover";
import { ReactFlowInstance } from "reactflow";
import { fetcher, truncate, useUniqueId } from "../lib/utils";

import { Children, useCallback, useEffect, useState } from "react";
import LoadingIcon from "../FlowBar/LoadingIcon";
import { TfiSave } from "react-icons/tfi";
import { usePages } from "@/hooks/usePages";

import { updateFlowData } from "../EdgebrixProvider/EdgebrixProvider";
import { useToken } from "@/hooks/useToken";
import { useCurrentFlow } from "@/hooks/useCurrentFlow";
import { useCurrentFolder } from "@/hooks/useCurrentFolder";

import styles from "../FlowBar/toolbar.module.css";
import toast from "react-hot-toast";
import { useStore } from "@/hooks/useEdg";

function FolderControler({
  children,
  reactFlowInstance,
}: {
  children?: React.ReactNode;
  reactFlowInstance: ReactFlowInstance | null;
}) {
  const [isSaving, setIsSaving] = useState<boolean>(false);

  const { flow, currentFlowId, setFlow } = useCurrentFlow();
  const { folder, currentFolderId, setFolder } = useCurrentFolder();

  const [rename, setRename] = useState<boolean>(false);

  const { setPages } = usePages();

  const { token } = useToken();

  const { toObject, addEdges, addNodes } = useStore();

  const saveFlow = async () => {
    console.log("saveFlow");
    //setIsSaving(true);
    const rw = toObject();
    console.log("rw", rw);
    const r = await updateFlowData(
      currentFolderId,
      currentFlowId,
      {},
      rw,
      token
    );
    console.log("r", r);
    // setIsSaving(false);

    if (!r) throw new Error("Save failed");
  };

  useEffect(() => {
    if (!folder?.name) return;

    setPages([
      { type: "home", name: "/" },
      { type: "folder", name: folder?.name },
      { type: "flow", name: flow?.name },
    ]);

    addNodes(flow?.data?.nodes || []);
    addEdges(flow?.data?.edges || []);
  }, [folder, flow]);
  return (
    <>
      <Popover.Root>
        <Popover.Trigger>
          <div className={styles.ToolbarItem}>
            <p className={styles.ToolbarLink}>
              {flow && <>{truncate(flow.name, 60)}</>}
              {/* {_folder && <>{truncate(_folder.name, 60)}</>} */}
            </p>
          </div>
        </Popover.Trigger>

        <Popover.Content>
          <div style={{ width: "400px", marginTop: "17px" }}>
            <FolderManager
              reactFlowInstance={reactFlowInstance}
              setRename={setRename}
            />
          </div>
        </Popover.Content>
      </Popover.Root>
      <Popover.Root>
        <Popover.Trigger>
          <div className={styles.ToolbarItem}>
            <div
              onClick={async () => {
                const t = saveFlow();
                toast.promise(t, {
                  loading: "Saving...",
                  error: "Saving failed...",
                  success: "Saved!",
                });
              }}
            >
              <span className={styles.AvatarImage}>
                <LoadingIcon color={"#fff"} inProgress={isSaving}>
                  <TfiSave
                    style={{
                      width: "18px",
                      height: "18px",
                      marginRight: "0px",
                    }}
                  />
                </LoadingIcon>
              </span>
            </div>
          </div>
        </Popover.Trigger>
      </Popover.Root>
      {Children.count(children) > 0 && (
        <>
          <Popover.Root key={useUniqueId()}>
            <Popover.Trigger>
              <div className={styles.ToolbarOther}>{children}</div>
            </Popover.Trigger>
          </Popover.Root>
        </>
      )}
    </>
  );
}

export { FolderControler };
