import { useEffect, useState } from "react";
import { baseUrl } from "./api";

interface Params {
  nodeSize: number;
  edgeWidth: number;
  arrowSize: number;
  fontSize: number;
}

export default function Analysis() {
  const [image, setImage] = useState("");
  const [params, setParams] = useState<Params>({
    nodeSize: 1600,
    edgeWidth: 1,
    arrowSize: 20,
    fontSize: 10,
  });
  const [showControlPanel, setShowControlPanel] = useState(false);
  const [loading, setLoading] = useState(false);

  // Function to generate and fetch the graph image
  async function loadImage() {
    setLoading(true);
    await fetch(`${baseUrl}analysis/image`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(params)
    })
      .then((resp) => resp.json())
      .then((data) => {
        setImage(data.image);
        setLoading(false);
      });
  }
  useEffect(() => {
    loadImage();
  }, []);

  return (
    <div className="stack column dropdown">
      <button onClick={() => setShowControlPanel(!showControlPanel)}>
        Parameters {showControlPanel ? "⮝" : "⮟"}
      </button>
      {showControlPanel && (
        <div id="control-panel">

          <label>Node Size:</label>
          <input
            type="range"
            min="500"
            max="3000"
            value={params.nodeSize}
            onChange={(evt) => setParams({ ...params, nodeSize: Number(evt.target.value) })}
            onMouseUp={() => loadImage()}
          />
          <span>{params.nodeSize}</span>

          <label>Font Size:</label>
          <input
            type="range"
            min="4"
            max="24"
            value={params.fontSize}
            onChange={(evt) => setParams({ ...params, fontSize: Number(evt.target.value) })}
            onMouseUp={() => loadImage()}
          />
          <span>{params.fontSize}</span>

          <label>Edge Width:</label>
          <input
            type="range"
            min="1"
            max="5"
            step="0.1"
            value={params.edgeWidth}
            onChange={(evt) => setParams({ ...params, edgeWidth: Number(evt.target.value) })}
            onMouseUp={() => loadImage()}
          />
          <span>{params.edgeWidth}</span>

          <label>Arrow Size:</label>
          <input
            type="range"
            min="10"
            max="50"
            value={params.arrowSize}
            onChange={(evt) => setParams({ ...params, arrowSize: Number(evt.target.value) })}
            onMouseUp={() => loadImage()}
          />
          <span>{params.arrowSize}</span>

        </div>
      )}
      {loading ? (
        <span className="loader"></span>
      ) : (
        <img src={"data:image/png;base64," + image} width="86%" />
      )}
    </div>
  );
}
