import { useCallback, useEffect, useMemo } from 'react';
import { Background, Controls, MiniMap, Panel, ReactFlow, addEdge, useEdgesState, useNodesState } from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import CustomEdge from './CustomEdge';
import CustomNode from './CustomNode';
import GraphControls from './GraphControls';
import { transformGraphData } from '../../utils/graphTransformers';

const nodeTypes = { serviceNode: CustomNode };
const edgeTypes = { default: CustomEdge };

export default function ArchitectureGraph({ graphData, onNodeClick }) {
  const transformed = useMemo(() => transformGraphData(graphData), [graphData]);
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);

  useEffect(() => {
    setNodes(transformed.nodes || []);
    setEdges(transformed.edges || []);
  }, [setEdges, setNodes, transformed]);

  const onConnect = useCallback((params) => setEdges((current) => addEdge(params, current)), [setEdges]);

  return (
    <div className="h-full min-h-[640px] overflow-hidden rounded-lg border border-white/10 bg-[#080b14]">
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
        onNodeClick={(_, node) => onNodeClick?.(node)}
        fitView
        minZoom={0.25}
        attributionPosition="bottom-left"
      >
        <Background color="#263144" gap={28} size={1} />
        <Controls />
        <MiniMap nodeColor={(node) => node.data?.color || '#38bdf8'} maskColor="rgba(8, 11, 20, 0.72)" />
        <Panel position="top-right">
          <GraphControls />
        </Panel>
      </ReactFlow>
    </div>
  );
}
