import React, { useState, useEffect, useRef } from 'react';
import { Users, Building2, Plus, Link2, Trash2, Download } from 'lucide-react';

const AIInfluenceMap = () => {
  const [nodes, setNodes] = useState([
    // Big Tech Companies
    { id: 1, name: 'Microsoft', type: 'company', x: 500, y: 150 },
    { id: 2, name: 'Google/Alphabet', type: 'company', x: 300, y: 150 },
    { id: 3, name: 'Nvidia', type: 'company', x: 700, y: 150 },
    { id: 4, name: 'Meta', type: 'company', x: 200, y: 250 },
    { id: 5, name: 'Amazon', type: 'company', x: 650, y: 250 },
    
    // AI Labs/Startups
    { id: 10, name: 'OpenAI', type: 'company', x: 500, y: 350 },
    { id: 11, name: 'Anthropic', type: 'company', x: 350, y: 450 },
    { id: 12, name: 'DeepMind', type: 'company', x: 300, y: 300 },
    { id: 13, name: 'xAI', type: 'company', x: 700, y: 400 },
    
    // Tech CEOs
    { id: 20, name: 'Satya Nadella', type: 'person', x: 500, y: 50 },
    { id: 21, name: 'Sundar Pichai', type: 'person', x: 300, y: 50 },
    { id: 22, name: 'Jensen Huang', type: 'person', x: 700, y: 50 },
    { id: 23, name: 'Mark Zuckerberg', type: 'person', x: 200, y: 150 },
    { id: 24, name: 'Andy Jassy', type: 'person', x: 650, y: 150 },
    
    // AI Lab Leaders
    { id: 30, name: 'Sam Altman', type: 'person', x: 550, y: 350 },
    { id: 31, name: 'Dario Amodei', type: 'person', x: 350, y: 550 },
    { id: 32, name: 'Daniela Amodei', type: 'person', x: 450, y: 550 },
    { id: 33, name: 'Demis Hassabis', type: 'person', x: 250, y: 350 },
    { id: 34, name: 'Elon Musk', type: 'person', x: 750, y: 450 },
    { id: 35, name: 'Ilya Sutskever', type: 'person', x: 450, y: 300 },
    { id: 36, name: 'Greg Brockman', type: 'person', x: 600, y: 300 },
    
    // Other Key Figures
    { id: 40, name: 'Lisa Su', type: 'person', x: 800, y: 150 },
    { id: 41, name: 'Mira Murati', type: 'person', x: 550, y: 450 },
  ]);
  
  const [links, setLinks] = useState([
    // CEOs to Companies
    { source: 20, target: 1, type: 'CEO' },
    { source: 21, target: 2, type: 'CEO' },
    { source: 22, target: 3, type: 'CEO & Founder' },
    { source: 23, target: 4, type: 'CEO & Founder' },
    { source: 24, target: 5, type: 'CEO' },
    { source: 40, target: 3, type: 'CEO (AMD)' },
    
    // AI Lab Leaders to Labs
    { source: 30, target: 10, type: 'CEO' },
    { source: 31, target: 11, type: 'CEO & Co-founder' },
    { source: 32, target: 11, type: 'President & Co-founder' },
    { source: 33, target: 12, type: 'CEO & Co-founder' },
    { source: 34, target: 13, type: 'Founder & Owner' },
    { source: 36, target: 10, type: 'Co-founder & CTO' },
    { source: 41, target: 10, type: 'Former CTO' },
    
    // Lab ownership/partnerships
    { source: 2, target: 12, type: 'Acquired 2014' },
    { source: 1, target: 10, type: '$13B Investment' },
    { source: 2, target: 11, type: '$2B Investment' },
    { source: 5, target: 11, type: '$4B Investment' },
    { source: 3, target: 11, type: 'Partnership' },
    
    // Historical connections - OpenAI founding
    { source: 34, target: 10, type: 'Co-founder (Left 2018)' },
    { source: 35, target: 10, type: 'Co-founder & Former Chief Scientist' },
    
    // Anthropic founding (ex-OpenAI)
    { source: 31, target: 10, type: 'Former VP Research' },
    { source: 32, target: 10, type: 'Former VP Safety' },
    
    // Key rivalries/tensions
    { source: 34, target: 30, type: 'Lawsuit' },
    { source: 10, target: 11, type: 'Competitors' },
    { source: 10, target: 13, type: 'Competitors' },
    { source: 10, target: 12, type: 'Competitors' },
    
    // Nvidia as enabler
    { source: 3, target: 10, type: 'GPU Provider' },
    { source: 3, target: 11, type: 'GPU Provider' },
    { source: 3, target: 13, type: '100K GPUs' },
    { source: 3, target: 1, type: 'Azure Partnership' },
    
    // Historical - recruiting battles
    { source: 34, target: 35, type: 'Recruited from Google' },
    { source: 33, target: 35, type: 'Competed to recruit' },
  ]);
  
  const [newNode, setNewNode] = useState({ name: '', type: 'person' });
  const [newLink, setNewLink] = useState({ source: '', target: '', type: '' });
  const [selectedNode, setSelectedNode] = useState(null);
  const [dragging, setDragging] = useState(null);
  
  const svgRef = useRef(null);
  const canvasWidth = 1000;
  const canvasHeight = 700;

  // Simulazione fisica per posizionamento automatico
  useEffect(() => {
    const interval = setInterval(() => {
      setNodes(prevNodes => {
        const newNodes = [...prevNodes];
        const alpha = 0.1;
        
        // Forza di repulsione tra nodi
        for (let i = 0; i < newNodes.length; i++) {
          for (let j = i + 1; j < newNodes.length; j++) {
            const dx = newNodes[j].x - newNodes[i].x;
            const dy = newNodes[j].y - newNodes[i].y;
            const distance = Math.sqrt(dx * dx + dy * dy) || 1;
            const force = 5000 / (distance * distance);
            
            const fx = (dx / distance) * force;
            const fy = (dy / distance) * force;
            
            newNodes[i].x -= fx * alpha;
            newNodes[i].y -= fy * alpha;
            newNodes[j].x += fx * alpha;
            newNodes[j].y += fy * alpha;
          }
        }
        
        // Forza di attrazione sui collegamenti
        links.forEach(link => {
          const sourceNode = newNodes.find(n => n.id === link.source);
          const targetNode = newNodes.find(n => n.id === link.target);
          
          if (sourceNode && targetNode) {
            const dx = targetNode.x - sourceNode.x;
            const dy = targetNode.y - sourceNode.y;
            const distance = Math.sqrt(dx * dx + dy * dy) || 1;
            const optimalDistance = 150;
            const force = (distance - optimalDistance) * 0.1;
            
            const fx = (dx / distance) * force;
            const fy = (dy / distance) * force;
            
            sourceNode.x += fx * alpha;
            sourceNode.y += fy * alpha;
            targetNode.x -= fx * alpha;
            targetNode.y -= fy * alpha;
          }
        });
        
        // Mantieni i nodi nell'area visibile
        newNodes.forEach(node => {
          node.x = Math.max(50, Math.min(canvasWidth - 50, node.x));
          node.y = Math.max(50, Math.min(canvasHeight - 50, node.y));
        });
        
        return newNodes;
      });
    }, 50);
    
    return () => clearInterval(interval);
  }, [links]);

  const addNode = () => {
    if (!newNode.name.trim()) return;
    
    const id = Math.max(0, ...nodes.map(n => n.id)) + 1;
    setNodes([...nodes, {
      id,
      name: newNode.name,
      type: newNode.type,
      x: Math.random() * (canvasWidth - 200) + 100,
      y: Math.random() * (canvasHeight - 200) + 100,
    }]);
    setNewNode({ name: '', type: 'person' });
  };

  const addLink = () => {
    if (!newLink.source || !newLink.target || newLink.source === newLink.target) return;
    
    setLinks([...links, {
      source: parseInt(newLink.source),
      target: parseInt(newLink.target),
      type: newLink.type || 'Connected'
    }]);
    setNewLink({ source: '', target: '', type: '' });
  };

  const deleteNode = (id) => {
    setNodes(nodes.filter(n => n.id !== id));
    setLinks(links.filter(l => l.source !== id && l.target !== id));
    setSelectedNode(null);
  };

  const deleteLink = (source, target) => {
    setLinks(links.filter(l => !(l.source === source && l.target === target)));
  };

  const handleMouseDown = (e, nodeId) => {
    e.stopPropagation();
    setDragging(nodeId);
    setSelectedNode(nodeId);
  };

  const handleMouseMove = (e) => {
    if (dragging) {
      const svg = svgRef.current;
      const rect = svg.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      setNodes(nodes.map(n => 
        n.id === dragging ? { ...n, x, y } : n
      ));
    }
  };

  const handleMouseUp = () => {
    setDragging(null);
  };

  const exportData = () => {
    const data = { nodes, links };
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ai-influence-map.json';
    a.click();
  };

  return (
    <div className="w-full h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 p-6">
      <div className="max-w-7xl mx-auto h-full flex flex-col gap-4">
        <div className="bg-white/10 backdrop-blur-lg rounded-lg p-4 border border-white/20">
          <h1 className="text-3xl font-bold text-white mb-2 flex items-center gap-3">
            <Users className="text-blue-400" size={32} />
            Mappa Influencer AI - Ecosistema Globale 2024-2025
          </h1>
          <p className="text-blue-200 text-sm">Le persone e aziende più influenti nel mondo dell'AI e le loro connessioni strategiche</p>
        </div>

        <div className="flex gap-4 flex-1 min-h-0">
          {/* Panel di controllo */}
          <div className="w-80 bg-white/10 backdrop-blur-lg rounded-lg p-4 border border-white/20 overflow-y-auto">
            {/* Aggiungi nodo */}
            <div className="mb-6">
              <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
                <Plus size={20} className="text-green-400" />
                Aggiungi Entità
              </h3>
              <input
                type="text"
                placeholder="Nome..."
                value={newNode.name}
                onChange={(e) => setNewNode({...newNode, name: e.target.value})}
                onKeyPress={(e) => e.key === 'Enter' && addNode()}
                className="w-full px-3 py-2 rounded bg-white/20 text-white placeholder-white/50 border border-white/30 mb-2"
              />
              <select
                value={newNode.type}
                onChange={(e) => setNewNode({...newNode, type: e.target.value})}
                className="w-full px-3 py-2 rounded bg-white/20 text-white border border-white/30 mb-2"
              >
                <option value="person">👤 Persona</option>
                <option value="company">🏢 Azienda</option>
              </select>
              <button
                onClick={addNode}
                className="w-full px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded font-medium transition-colors"
              >
                Aggiungi
              </button>
            </div>

            {/* Aggiungi collegamento */}
            <div className="mb-6">
              <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
                <Link2 size={20} className="text-blue-400" />
                Aggiungi Collegamento
              </h3>
              <select
                value={newLink.source}
                onChange={(e) => setNewLink({...newLink, source: e.target.value})}
                className="w-full px-3 py-2 rounded bg-white/20 text-white border border-white/30 mb-2"
              >
                <option value="">Da...</option>
                {nodes.map(n => (
                  <option key={n.id} value={n.id}>
                    {n.type === 'person' ? '👤' : '🏢'} {n.name}
                  </option>
                ))}
              </select>
              <select
                value={newLink.target}
                onChange={(e) => setNewLink({...newLink, target: e.target.value})}
                className="w-full px-3 py-2 rounded bg-white/20 text-white border border-white/30 mb-2"
              >
                <option value="">A...</option>
                {nodes.map(n => (
                  <option key={n.id} value={n.id}>
                    {n.type === 'person' ? '👤' : '🏢'} {n.name}
                  </option>
                ))}
              </select>
              <input
                type="text"
                placeholder="Tipo relazione (CEO, Founder...)"
                value={newLink.type}
                onChange={(e) => setNewLink({...newLink, type: e.target.value})}
                onKeyPress={(e) => e.key === 'Enter' && addLink()}
                className="w-full px-3 py-2 rounded bg-white/20 text-white placeholder-white/50 border border-white/30 mb-2"
              />
              <button
                onClick={addLink}
                className="w-full px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded font-medium transition-colors"
              >
                Collega
              </button>
            </div>

            {/* Lista collegamenti */}
            <div className="mb-4">
              <h3 className="text-white font-semibold mb-2">Collegamenti ({links.length})</h3>
              <div className="space-y-1 max-h-40 overflow-y-auto">
                {links.map((link, idx) => {
                  const source = nodes.find(n => n.id === link.source);
                  const target = nodes.find(n => n.id === link.target);
                  return (
                    <div key={idx} className="bg-white/10 rounded p-2 text-xs text-white flex items-center justify-between">
                      <span className="flex-1 truncate">
                        {source?.name} → {target?.name}
                        <span className="text-blue-300 ml-1">({link.type})</span>
                      </span>
                      <button
                        onClick={() => deleteLink(link.source, link.target)}
                        className="text-red-400 hover:text-red-300"
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Export */}
            <button
              onClick={exportData}
              className="w-full px-4 py-2 bg-purple-500 hover:bg-purple-600 text-white rounded font-medium transition-colors flex items-center justify-center gap-2"
            >
              <Download size={16} />
              Esporta JSON
            </button>
          </div>

          {/* Canvas SVG */}
          <div className="flex-1 bg-white/10 backdrop-blur-lg rounded-lg border border-white/20 overflow-hidden">
            <svg
              ref={svgRef}
              width="100%"
              height="100%"
              viewBox={`0 0 ${canvasWidth} ${canvasHeight}`}
              onMouseMove={handleMouseMove}
              onMouseUp={handleMouseUp}
              onMouseLeave={handleMouseUp}
              className="cursor-move"
            >
              <defs>
                <marker
                  id="arrowhead"
                  markerWidth="10"
                  markerHeight="10"
                  refX="8"
                  refY="3"
                  orient="auto"
                >
                  <polygon points="0 0, 10 3, 0 6" fill="#60a5fa" />
                </marker>
              </defs>

              {/* Collegamenti */}
              {links.map((link, idx) => {
                const source = nodes.find(n => n.id === link.source);
                const target = nodes.find(n => n.id === link.target);
                if (!source || !target) return null;

                const dx = target.x - source.x;
                const dy = target.y - source.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                const offset = 40;
                const targetX = target.x - (dx / distance) * offset;
                const targetY = target.y - (dy / distance) * offset;

                const midX = (source.x + targetX) / 2;
                const midY = (source.y + targetY) / 2;

                return (
                  <g key={idx}>
                    <line
                      x1={source.x}
                      y1={source.y}
                      x2={targetX}
                      y2={targetY}
                      stroke="#60a5fa"
                      strokeWidth="2"
                      markerEnd="url(#arrowhead)"
                    />
                    <text
                      x={midX}
                      y={midY - 5}
                      fill="#93c5fd"
                      fontSize="11"
                      textAnchor="middle"
                      className="pointer-events-none font-medium"
                    >
                      {link.type}
                    </text>
                  </g>
                );
              })}

              {/* Nodi */}
              {nodes.map(node => (
                <g
                  key={node.id}
                  onMouseDown={(e) => handleMouseDown(e, node.id)}
                  className="cursor-pointer"
                >
                  <circle
                    cx={node.x}
                    cy={node.y}
                    r="35"
                    fill={node.type === 'person' ? '#3b82f6' : '#8b5cf6'}
                    stroke={selectedNode === node.id ? '#fbbf24' : '#ffffff'}
                    strokeWidth={selectedNode === node.id ? 4 : 2}
                    className="transition-all"
                  />
                  <text
                    x={node.x}
                    y={node.y - 20}
                    fill="white"
                    fontSize="24"
                    textAnchor="middle"
                    className="pointer-events-none"
                  >
                    {node.type === 'person' ? '👤' : '🏢'}
                  </text>
                  <text
                    x={node.x}
                    y={node.y + 50}
                    fill="white"
                    fontSize="13"
                    textAnchor="middle"
                    fontWeight="600"
                    className="pointer-events-none"
                  >
                    {node.name}
                  </text>
                  {selectedNode === node.id && (
                    <g onClick={(e) => { e.stopPropagation(); deleteNode(node.id); }}>
                      <circle
                        cx={node.x + 25}
                        cy={node.y - 25}
                        r="12"
                        fill="#ef4444"
                        className="cursor-pointer hover:fill-red-600"
                      />
                      <text
                        x={node.x + 25}
                        y={node.y - 21}
                        fill="white"
                        fontSize="16"
                        textAnchor="middle"
                        className="pointer-events-none"
                      >
                        ×
                      </text>
                    </g>
                  )}
                </g>
              ))}
            </svg>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AIInfluenceMap;
