import { useEdgebrix } from "@/hooks/useEdgebrix";
import { useUser } from "@/hooks/useUser";
import { BookOpenIcon, CogIcon } from "@heroicons/react/20/solid";
import { SpeedDial } from "primereact/speeddial";
import { useCallback, useEffect, useMemo, useState } from "react";

import ReactFlow, {
  addEdge,
  FitViewOptions,
  applyNodeChanges,
  applyEdgeChanges,
  Node,
  Edge,
  NodeChange,
  EdgeChange,
  Connection,
  ReactFlowProvider,
  Panel,
  useReactFlow,
  Background,
  MarkerType,
  useOnSelectionChange,
} from "reactflow";
import { Menu, TriggersSelect } from "../Actions";
import { ActionsDropdown } from "../Actions/ActionsDropdown";
import { ActionsSelect } from "../Actions/ActionsSelect";
import { Admin } from "../Admin";
import { Collaboration } from "../Collaboration";
import { FlowBar, Separator } from "../FlowBar";
import { FolderControler } from "../FlowManager";

import { BasicNode } from "../Nodes/Basic";
import { WebhookNode } from "../Nodes/Webhook";
import { NotificationFeed } from "../Notification";

const items = [
  {
    label: "Add",
    icon: <CogIcon />,
    command: () => {},
  },
  {
    label: "Update",
    icon: "pi pi-refresh",
    command: () => {},
  },
  {
    label: "Delete",
    icon: "pi pi-trash",
    command: () => {},
  },
  {
    label: "React Website",
    icon: "pi pi-external-link",
    command: () => {
      window.location.href = "https://facebook.github.io/react/";
    },
  },
];

const initialNodes: Node[] = [
  { id: "1", data: { label: "Node 1" }, position: { x: 5, y: 5 } },
  { id: "2", data: { label: "Node 2" }, position: { x: 5, y: 100 } },
];

const initialEdges: Edge[] = [{ id: "e1-2", source: "1", target: "2" }];

const fitViewOptions: FitViewOptions = {
  padding: 0.2,
};

function Flow() {
  const { isLoading } = useUser();

  useEffect(() => {
    console.log("isLoading", isLoading);
    setEdges([]);
    setNodes([]);
  }, [isLoading]);

  const [nodes, setNodes] = useState<Node[]>([]);
  const [edges, setEdges] = useState<Edge[]>([]);

  const onNodesChange = useCallback(
    (changes: NodeChange[]) =>
      setNodes((nds) => applyNodeChanges(changes, nds)),
    [setNodes]
  );
  const onEdgesChange = useCallback(
    (changes: EdgeChange[]) =>
      setEdges((eds) => applyEdgeChanges(changes, eds)),
    [setEdges]
  );
  const onConnect = useCallback(
    (connection: Connection) => setEdges((eds) => addEdge(connection, eds)),
    [setEdges]
  );

  useOnSelectionChange({
    onChange: ({ nodes, edges }: { nodes: Node[]; edges: Edge[] }): void => {
      console.log("changed selection", nodes, edges);
    },
  });

  const rf = useReactFlow();

  const { addNodes } = rf;

  const { edgebrix, setEdgebrix } = useEdgebrix();

  //const nodeTypes = { basic: BasicNode };

  const nodeTypes = useMemo(
    () => ({
      basic: BasicNode,
      webhook: WebhookNode,
    }),
    []
  );

  useEffect(() => {
    console.log("edgebrix", edgebrix);
    setEdgebrix(rf);
  }, [rf]);

  return (
    <ReactFlow
      nodeTypes={nodeTypes}
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      fitView
      fitViewOptions={fitViewOptions}
    >
      <Panel position="top-left">
        <FlowBar
          reactFlowInstance={rf}
          replaceFlowWith={"dashboard"}
          replaceFolderWith={"project"}
        >
          <FolderControler reactFlowInstance={rf} />
          <Separator style={{ margin: "0 15px" }} />
          <TriggersSelect />
          <ActionsSelect />

          <Separator style={{ margin: "0 15px" }} />
          {/* <Menu />
          <Separator style={{ margin: "0 15px" }} /> */}
          <Collaboration excludeViewer={true} />
          {/* <Separator style={{ margin: "0 15px" }} />
          <NotificationFeed /> */}
          <Separator style={{ margin: "0 15px" }} />
          <Admin />

          {/* <div
            onClick={() => {
              addNodes({
                id: "3",
                data: { label: "Node 3" },
                position: { x: 5, y: 200 },
                type: "basic",
              });
            }}
          >
            Add{" "}
          </div> */}
        </FlowBar>
      </Panel>

      <Background />
    </ReactFlow>
  );
}

export default function FlowProvider() {
  return (
    <>
      <ReactFlowProvider>
        <Flow />
        {/* <SpeedDial
          model={items}
          direction="up"
          showIcon={
            <BookOpenIcon style={{ width: "1.5rem", height: "1.5rem" }} />
          }
          hideIcon={<CogIcon />}
          style={{ bottom: 20, right: 20 }}
        /> */}
      </ReactFlowProvider>
    </>
  );
}
