import React, { useState, useEffect, useCallback } from "react";
import ReactFlow, {
    addEdge,
    Controls,
    Background,
} from "reactflow";
import "reactflow/dist/style.css";

const fetchNodes = async () => {
    const response = await fetch("/api/workflow");
    return response.json();
};

const saveWorkflow = async (workflow) => {
    await fetch("/api/workflow", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(workflow),
    });
};

export default function FlowEditor() {
    const [elements, setElements] = useState([]);

    useEffect(() => {
        fetchNodes().then((data) => setElements([...data.nodes, ...data.edges]));
    }, []);

    const onConnect = useCallback(
        (params) => {
            const newEdge = { id: `e${params.source}-${params.target}`, ...params };
            setElements((els) => [...els, newEdge]);
            saveWorkflow({ nodes: elements.filter(e => e.type), edges: [...elements.filter(e => !e.type), newEdge] });
        },
        [elements]
    );

    return (
        <div style={{ width: "100vw", height: "100vh" }}>
            <ReactFlow elements={elements} onConnect={onConnect}>
                <Controls />
                <Background />
            </ReactFlow>
        </div>
    );
}
