import { Input, Modal } from "antd";
import { graphContext, type NodeContext } from "./Graph";
import { useContext, useState } from "react";

export default function NodeRenameModal({
  nodeContext,
  renameModalOpened, 
  openRenameModal
} : {
  nodeContext: NodeContext,
  renameModalOpened: boolean, 
  openRenameModal: React.Dispatch<React.SetStateAction<boolean>>
}) {
  if(!renameModalOpened){
    return;
  }
  const [nodeName, setSelectedNodeName] = useState(nodeContext.nodeName);
  const graphContextValue = useContext(graphContext)!;        

  function renameNode() {
    const node = graphContextValue.graph.nodes.find(n => n.id === nodeContext.nodeId);
    if (!node) {
      return;
    }
    node.label = nodeName;
    graphContextValue.setGraph(prev => ({ ...prev, nodes: graphContextValue.graph.nodes }));
    openRenameModal(false);
  }

  return (
    <Modal
      title="Rename"
      open={renameModalOpened}
      onOk={() => renameNode()}
      onCancel={() => openRenameModal(false)}
    >
      <Input value={nodeName} onChange={(e) => setSelectedNodeName(e.target.value)} />
    </Modal>
  )
}