"use client";

import { useRef, useMemo, useState, useCallback, useEffect } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls, Float, Html } from "@react-three/drei";
import * as THREE from "three";

interface AgentInfo {
  name: string;
  role: string;
  description: string;
  capabilities: string[];
  stats: { active: string; tasks: string; efficiency: string };
}

const agentData: Record<string, AgentInfo> = {
  CEO: {
    name: "AI Director",
    role: "Strategic Leadership",
    description: "Orchestrates entire AI workforce operations",
    capabilities: ["Workforce Planning", "Resource Allocation", "Performance Monitoring", "Strategic Decisions"],
    stats: { active: "7/7", tasks: "1.2K/day", efficiency: "99.9%" }
  },
  Sales: {
    name: "Sales Team",
    role: "Revenue Generation",
    description: "Qualifies leads, nurtures prospects, closes deals 24/7",
    capabilities: ["Lead Qualification", "Email Sequences", "Demo Scheduling", "Deal Closing"],
    stats: { active: "8/8", tasks: "347/day", efficiency: "98.7%" }
  },
  Marketing: {
    name: "Marketing Hub",
    role: "Brand & Growth",
    description: "Content creation, campaigns, and performance optimization",
    capabilities: ["Content Generation", "SEO Optimization", "Ad Management", "Analytics"],
    stats: { active: "6/6", tasks: "189/day", efficiency: "97.2%" }
  },
  Support: {
    name: "Support Squad",
    role: "Customer Success",
    description: "Instant responses and ticket resolution at scale",
    capabilities: ["24/7 Chat", "Ticket Resolution", "Knowledge Base", "Sentiment Analysis"],
    stats: { active: "12/12", tasks: "523/day", efficiency: "99.1%" }
  },
  Operations: {
    name: "Ops Engine",
    role: "Process Automation",
    description: "Workflow automation and resource optimization",
    capabilities: ["Process Automation", "Resource Planning", "Quality Control", "Reporting"],
    stats: { active: "10/10", tasks: "445/day", efficiency: "98.5%" }
  },
  Finance: {
    name: "Finance Core",
    role: "Financial Management",
    description: "Bookkeeping, invoicing, and financial analysis",
    capabilities: ["Invoicing", "Expense Tracking", "Financial Reports", "Budget Management"],
    stats: { active: "4/4", tasks: "128/day", efficiency: "99.8%" }
  },
  HR: {
    name: "People Hub",
    role: "Human Resources",
    description: "Recruitment, onboarding, and employee management",
    capabilities: ["Resume Screening", "Interview Scheduling", "Onboarding", "Performance Reviews"],
    stats: { active: "5/5", tasks: "87/day", efficiency: "96.8%" }
  }
};

// Agent Node Component
function AgentNode({
  position,
  color,
  agentKey,
  onActivate,
  isActive
}: {
  position: [number, number, number];
  color: string;
  agentKey: string;
  onActivate: (key: string) => void;
  isActive: boolean;
}) {
  const meshRef = useRef<THREE.Mesh>(null);
  const pulsePhase = Math.random() * Math.PI * 2;
  const [hovered, setHovered] = useState(false);

  useFrame((state) => {
    if (meshRef.current) {
      const pulse = Math.sin(state.clock.elapsedTime * 2 + pulsePhase) * 0.1 + 1;
      const baseScale = isActive ? 0.4 : 0.3;
      const hoverScale = hovered ? 0.35 : 0;
      meshRef.current.scale.setScalar(pulse * baseScale + hoverScale);
    }
  });

  const handleClick = useCallback(() => {
    onActivate(agentKey);
  }, [agentKey, onActivate]);

  const info = agentData[agentKey];

  return (
    <Float speed={2} rotationIntensity={0.5} floatIntensity={0.5}>
      <group position={position} onClick={handleClick}>
        <mesh
          ref={meshRef}
          onPointerOver={() => setHovered(true)}
          onPointerOut={() => setHovered(false)}
        >
          <sphereGeometry args={[1, 32, 32]} />
          <meshStandardMaterial
            color={color}
            emissive={color}
            emissiveIntensity={isActive ? 1 : 0.5}
            roughness={0.2}
            metalness={0.8}
          />
          {/* Glow effect */}
          <pointLight color={color} intensity={isActive ? 4 : 2} distance={isActive ? 5 : 3} />
        </mesh>

        {/* Active indicator ring */}
        {isActive && (
          <mesh>
            <ringGeometry args={[1.5, 1.7, 32]} />
            <meshBasicMaterial color={color} transparent opacity={0.3} />
          </mesh>
        )}

        {/* Agent info tooltip */}
        {hovered && info && (
          <Html
            position={[0, 2, 0]}
            center
            distanceFactor={8}
            style={{ pointerEvents: 'none' }}
          >
            <div className="bg-obsidian/90 backdrop-blur-xl border border-electric-cyan/30 rounded-xl p-4 min-w-[250px] shadow-2xl">
              <div className="font-space-grotesk font-bold text-electric-cyan mb-1">{info.name}</div>
              <div className="text-xs text-muted-white mb-2">{info.role}</div>
              <div className="flex gap-4 mb-3">
                <div>
                  <div className="text-[10px] text-muted-white">{info.stats.active}</div>
                  <div className="text-xs text-soft-emerald">Active</div>
                </div>
                <div>
                  <div className="text-[10px] text-muted-white">{info.stats.tasks}</div>
                  <div className="text-xs text-soft-emerald">Tasks</div>
                </div>
                <div>
                  <div className="text-[10px] text-muted-white">{info.stats.efficiency}</div>
                  <div className="text-xs text-soft-emerald">Efficiency</div>
                </div>
              </div>
              <div className="text-[10px] text-warm-white opacity-70">
                Click to see details
              </div>
            </div>
          </Html>
        )}
      </group>
    </Float>
  );
}

// Connection Lines
function ConnectionLines({ nodes, activeAgent }: { nodes: Array<{ position: [number, number, number]; color: string; key: string }>; activeAgent: string | null }) {
  const linesRef = useRef<THREE.Group>(null);

  useFrame((state) => {
    if (linesRef.current) {
      linesRef.current.children.forEach((line, i) => {
        const material = line as THREE.Line;
        if (material.userData.originalOpacity === undefined) {
          material.userData.originalOpacity = (material.material as THREE.LineBasicMaterial).opacity;
        }
        const pulse = Math.sin(state.clock.elapsedTime + i * 0.5) * 0.3 + 0.7;
        (material.material as THREE.LineBasicMaterial).opacity = pulse * material.userData.originalOpacity;
      });
    }
  });

  return (
    <group ref={linesRef}>
      {Array.from({ length: Math.min(nodes.length * (nodes.length - 1) / 2, 20) }).map((_, i) => {
        const startNode = nodes[i % nodes.length];
        const endNode = nodes[(i + 1) % nodes.length];
        const isActiveConnection = activeAgent === startNode.key || activeAgent === endNode.key;

        return (
          <line key={i}>
            <bufferGeometry
              attach="geometry"
              onUpdate={(geometry) => {
                geometry.setFromPoints([
                  new THREE.Vector3(...startNode.position),
                  new THREE.Vector3(...endNode.position)
                ]);
              }}
            />
            <lineBasicMaterial
              attach="material"
              color={isActiveConnection ? "#00D9A5" : "#00F0FF"}
              transparent
              opacity={isActiveConnection ? 0.6 : 0.3}
            />
          </line>
        );
      })}
    </group>
  );
}

// Particle Field
function ParticleField() {
  const particlesRef = useRef<THREE.Points>(null);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  const particleCount = isMobile ? 200 : 500;

  const positions = useMemo(() => {
    const pos = new Float32Array(particleCount * 3);
    for (let i = 0; i < particleCount * 3; i += 3) {
      pos[i] = (Math.random() - 0.5) * 50;
      pos[i + 1] = (Math.random() - 0.5) * 50;
      pos[i + 2] = (Math.random() - 0.5) * 50;
    }
    return pos;
  }, [particleCount]);

  useFrame((state) => {
    if (particlesRef.current) {
      particlesRef.current.rotation.y = state.clock.elapsedTime * 0.05;
      particlesRef.current.rotation.x = Math.sin(state.clock.elapsedTime * 0.03) * 0.1;
    }
  });

  return (
    <points ref={particlesRef}>
      <bufferGeometry>
        <bufferAttribute
          attach="attributes-position"
          count={particleCount}
          array={positions}
          itemSize={3}
          args={[positions, 3]}
        />
      </bufferGeometry>
      <pointsMaterial
        size={0.05}
        color="#00F0FF"
        transparent
        opacity={0.6}
        sizeAttenuation
      />
    </points>
  );
}

// Grid Floor
function GridFloor() {
  return (
    <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -5, 0]}>
      <planeGeometry args={[100, 100]} />
      <meshBasicMaterial
        color="#00F0FF"
        transparent
        opacity={0.05}
        wireframe
      />
    </mesh>
  );
}

// Main Scene
function Scene({ activeAgent, onAgentActivate }: { activeAgent: string | null; onAgentActivate: (key: string) => void }) {
  const agentNodes = [
    { position: [-3, 2, 0] as [number, number, number], color: "#00F0FF", key: "CEO" },
    { position: [-1, 1, 2] as [number, number, number], color: "#00D9A5", key: "Sales" },
    { position: [1, 1, -2] as [number, number, number], color: "#00F0FF", key: "Marketing" },
    { position: [3, 2, 0] as [number, number, number], color: "#00D9A5", key: "Support" },
    { position: [0, -1, 0] as [number, number, number], color: "#00F0FF", key: "Operations" },
    { position: [-2, 0, -2] as [number, number, number], color: "#00D9A5", key: "Finance" },
    { position: [2, 0, 2] as [number, number, number], color: "#00F0FF", key: "HR" }
  ];

  return (
    <>
      {/* Lighting */}
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} intensity={1} color="#00F0FF" />
      <pointLight position={[-10, -10, -10]} intensity={0.5} color="#00D9A5" />

      {/* Components */}
      <GridFloor />
      <ParticleField />
      <ConnectionLines nodes={agentNodes} activeAgent={activeAgent} />
      {agentNodes.map((node) => (
        <AgentNode
          key={node.key}
          position={node.position}
          color={node.color}
          agentKey={node.key}
          isActive={activeAgent === node.key}
          onActivate={onAgentActivate}
        />
      ))}
    </>
  );
}

// Main Component
export function NeuralWorkforceTree() {
  const [activeAgent, setActiveAgent] = useState<string | null>(null);

  const handleAgentActivate = useCallback((key: string) => {
    setActiveAgent(activeAgent === key ? null : key);
  }, [activeAgent]);

  return (
    <div className="w-full h-full">
      <Canvas
        camera={{ position: [0, 5, 15], fov: 50 }}
        gl={{
          antialias: true,
          alpha: true,
          powerPreference: "high-performance"
        }}
        className="cursor-pointer"
      >
        <Scene activeAgent={activeAgent} onAgentActivate={handleAgentActivate} />
        <OrbitControls
          enableZoom={true}
          enablePan={true}
          enableRotate={true}
          maxPolarAngle={Math.PI / 2}
          minPolarAngle={Math.PI / 3}
          minDistance={5}
          maxDistance={30}
        />
      </Canvas>

      {/* Agent Detail Panel */}
      {activeAgent && (
        <div className="absolute top-4 right-4 bg-obsidian/90 backdrop-blur-xl border border-electric-cyan/30 rounded-2xl p-6 max-w-sm">
          <button
            onClick={() => setActiveAgent(null)}
            className="absolute top-2 right-2 text-muted-white hover:text-warm-white"
          >
            ✕
          </button>
          <h3 className="font-space-grotesk font-bold text-electric-cyan text-xl mb-2">
            {agentData[activeAgent].name}
          </h3>
          <p className="text-sm text-warm-white mb-4">{agentData[activeAgent].description}</p>
          <div className="space-y-2 mb-4">
            <div className="text-xs text-muted-white">Capabilities:</div>
            {agentData[activeAgent].capabilities.map((cap, i) => (
              <div key={i} className="flex items-center gap-2 text-sm text-warm-white">
                <div className="w-1.5 h-1.5 rounded-full bg-soft-emerald" />
                {cap}
              </div>
            ))}
          </div>
          <div className="grid grid-cols-3 gap-4 pt-4 border-t border-white/10">
            <div>
              <div className="text-xs text-muted-white">{agentData[activeAgent].stats.active}</div>
              <div className="text-xs text-soft-emerald">Active</div>
            </div>
            <div>
              <div className="text-xs text-muted-white">{agentData[activeAgent].stats.tasks}</div>
              <div className="text-xs text-soft-emerald">Tasks</div>
            </div>
            <div>
              <div className="text-xs text-muted-white">{agentData[activeAgent].stats.efficiency}</div>
              <div className="text-xs text-soft-emerald">Efficiency</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
