import { useDroppable } from "@dnd-kit/core";
import { useState } from "react";
import ReactFlow, {
  Background,
  Controls,
  ReactFlowInstance,
} from "react-flow-renderer";

import useStore from "../../lib/FlowEditor/FlowEditorStore";

import LedNode from "./nodes/IO/LedNode";
import SensorNode from "./nodes/IO/SensorNode";

import DelayNode from "./nodes/Logic/DelayNode";
import FinishNode from "./nodes/Logic/FinishNode";
import MathNode from "./nodes/Logic/MathNode";
import StartNode from "./nodes/Logic/StartNode";

const nodeTypes = {
  led: LedNode,
  sensor: SensorNode,
  delay: DelayNode,
  math: MathNode,
  finish: FinishNode,
  start: StartNode,
};

const Flow = () => {
  const [reactFlowInstance, setReactFlowInstance] =
    useState<ReactFlowInstance>();

  const onInit = (rfi: ReactFlowInstance) => {
    setReactFlowInstance(rfi);
  };

  const { isOver, setNodeRef } = useDroppable({ id: "flow" });

  const { nodes, edges, onNodesChange, onEdgesChange, onConnect } = useStore();

  return (
    <div ref={setNodeRef} className="flow h-screen w-full">
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        onInit={onInit}
        fitView
        snapToGrid={true}
      >
        <Controls />
        <Background />
      </ReactFlow>
    </div>
  );
};

export default Flow;
