import React, { useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import {
  Activity,
  Cloud,
  Cpu,
  Globe,
  HardDrive,
  Headphones,
  Rocket,
  Server,
  Shield,
  Zap,
} from 'lucide-react';

type NexusFeatureIcon = 'bolt' | 'shield' | 'cloud' | 'wp' | 'headphones' | 'rocket';
type NexusFeature = { title: string; desc: string; icon: NexusFeatureIcon };
type NexusQuickStat = { label: string; value: string };

type NexusNode = {
  id: string;
  title: string;
  desc: string;
  icon: React.ComponentType<{ size?: number; className?: string; style?: React.CSSProperties }>;
  color: string;
  x: number;
  y: number;
  stats: NexusQuickStat[];
};

export type NetworkNexusProps = {
  badgeText?: string;
  heading?: string;
  description?: string;
  coreLabel?: string;
  features?: NexusFeature[];
  quickStats?: NexusQuickStat[];
};

const DEFAULT_COPY = {
  badgeText: 'زیرساخت ابری هوشمند و یکپارچه',
  heading: 'معماری شبکه و سرورها',
  description:
    'یک شبکه عظیم و به‌هم پیوسته از قدرتمندترین سرورهای جهان؛ پایداری بی‌نظیر، امنیت لایه‌ای و سرعت حداکثری برای کسب‌وکار شما.',
  coreLabel: 'CORE HUB',
};

const DEFAULT_NODES: NexusNode[] = [
  {
    id: 'cloud',
    title: 'هاست ابری اختصاصی',
    desc: 'پایداری ۹۹.۹۹٪ با زیرساخت تمام ابری و هاردهای NVMe Enterprise',
    icon: Cloud,
    color: '#3b82f6',
    x: 0,
    y: -220,
    stats: [
      { label: 'Uptime', value: '99.99%' },
      { label: 'Storage', value: 'NVMe SSD' },
    ],
  },
  {
    id: 'dedicated',
    title: 'سرور اختصاصی',
    desc: 'بالاترین قدرت پردازشی با سرورهای فیزیکی اختصاصی در بهترین دیتاسنترها',
    icon: Server,
    color: '#ef4444',
    x: -300,
    y: -100,
    stats: [
      { label: 'CPU', value: 'Intel/AMD Dual' },
      { label: 'Network', value: '10 Gbps' },
    ],
  },
  {
    id: 'vps',
    title: 'سرور مجازی (VPS)',
    desc: 'منابع کاملاً اختصاصی، کنترل کامل روت و تنوع سیستم‌عامل‌ها',
    icon: HardDrive,
    color: '#10b981',
    x: 300,
    y: -100,
    stats: [
      { label: 'RAM', value: 'Up to 128GB' },
      { label: 'Root Access', value: 'Full' },
    ],
  },
  {
    id: 'security',
    title: 'امنیت و آنتی‌دیداس',
    desc: 'محافظت هوشمند لایه ۷ در برابر بزرگ‌ترین حملات سایبری',
    icon: Shield,
    color: '#8b5cf6',
    x: -220,
    y: 160,
    stats: [
      { label: 'DDoS Protection', value: 'Up to 2Tbps' },
      { label: 'WAF', value: 'Enabled' },
    ],
  },
  {
    id: 'cdn',
    title: 'شبکه توزیع محتوا (CDN)',
    desc: 'بارگذاری در کسری از ثانیه با توزیع جهانی اطلاعات در سرورهای لبه',
    icon: Globe,
    color: '#f59e0b',
    x: 220,
    y: 160,
    stats: [
      { label: 'Global PoPs', value: '150+' },
      { label: 'Latency', value: '< 20ms' },
    ],
  },
];

const NODE_POSITIONS = [
  { x: 0, y: -220 },
  { x: -300, y: -100 },
  { x: 300, y: -100 },
  { x: -220, y: 160 },
  { x: 220, y: 160 },
];

const NODE_COLORS = ['#3b82f6', '#ef4444', '#10b981', '#8b5cf6', '#f59e0b'];

function iconForFeature(icon: NexusFeatureIcon): NexusNode['icon'] {
  switch (icon) {
    case 'bolt':
      return Zap;
    case 'shield':
      return Shield;
    case 'cloud':
      return Cloud;
    case 'wp':
      return Globe;
    case 'headphones':
      return Headphones;
    case 'rocket':
      return Rocket;
  }
}

export function NetworkNexus(props: NetworkNexusProps) {
  const [activeService, setActiveService] = useState<string | null>(null);

  const copy = {
    badgeText: props.badgeText ?? DEFAULT_COPY.badgeText,
    heading: props.heading ?? DEFAULT_COPY.heading,
    description: props.description ?? DEFAULT_COPY.description,
    coreLabel: props.coreLabel ?? DEFAULT_COPY.coreLabel,
  };

  const services = useMemo<NexusNode[]>(() => {
    if (!props.features?.length) return DEFAULT_NODES;

    const nodesCount = Math.min(5, props.features.length);
    const stats = props.quickStats ?? [];

    return props.features.slice(0, nodesCount).map((feature, idx) => {
      const a = stats.length ? stats[idx % stats.length] : undefined;
      const b = stats.length ? stats[(idx + 1) % stats.length] : undefined;
      const nodeStats = [a, b].filter(Boolean) as NexusQuickStat[];

      return {
        id: `feature-${idx}`,
        title: feature.title,
        desc: feature.desc,
        icon: iconForFeature(feature.icon),
        color: NODE_COLORS[idx] ?? '#3b82f6',
        x: NODE_POSITIONS[idx]?.x ?? 0,
        y: NODE_POSITIONS[idx]?.y ?? 0,
        stats: nodeStats.length
          ? nodeStats
          : [
              { label: 'Uptime', value: '99.99%' },
              { label: 'Storage', value: 'NVMe SSD' },
            ],
      };
    });
  }, [props.features, props.quickStats]);

  return (
    <section className="relative min-h-[120vh] flex flex-col items-center justify-center py-20" dir="rtl">
      {/* Background Grid Pattern */}
      <div
        className="absolute inset-0 opacity-10"
        style={{
          backgroundImage: 'radial-gradient(#4f46e5 1px, transparent 1px)',
          backgroundSize: '40px 40px',
          backgroundPosition: '-19px -19px',
        }}
      />

      <div className="text-center mb-16 z-20">
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          whileInView={{ opacity: 1, scale: 1 }}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-indigo-500/10 border border-indigo-500/30 text-indigo-400 text-sm mb-6"
        >
          <Activity className="w-4 h-4" />
          <span>{copy.badgeText}</span>
        </motion.div>
        <h2 className="text-4xl md:text-5xl font-bold mb-6 text-transparent bg-clip-text bg-gradient-to-r from-white via-indigo-200 to-gray-400">
          {copy.heading}
        </h2>
        <p className="text-gray-400 text-lg max-w-2xl mx-auto leading-relaxed">{copy.description}</p>
      </div>

      <div className="relative flex items-center justify-center w-full max-w-[1000px] h-[600px] mt-10 scale-[0.6] sm:scale-75 md:scale-100 transition-transform duration-500">
        {/* SVG Connections */}
        <svg
          className="absolute inset-0 w-full h-full pointer-events-none"
          viewBox="-500 -300 1000 600"
          preserveAspectRatio="xMidYMid meet"
        >
          <defs>
            <radialGradient id="coreGlow" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor="rgba(99, 102, 241, 0.4)" />
              <stop offset="100%" stopColor="rgba(99, 102, 241, 0)" />
            </radialGradient>
          </defs>

          {/* Central Glow Effect */}
          <circle cx="0" cy="0" r="150" fill="url(#coreGlow)" className="animate-pulse" />

          {/* Static paths and animated data streams */}
          {services.map((service) => {
            // Cubic bezier curve path for a "cable" look
            const pathD = `M 0 0 C ${service.x * 0.5} 0, ${service.x * 0.8} ${service.y * 0.8}, ${service.x} ${service.y}`;
            const isActive = activeService === service.id;
            const opacity = activeService ? (isActive ? 1 : 0.2) : 0.6;

            return (
              <g key={`path-${service.id}`} className="transition-opacity duration-300" style={{ opacity }}>
                {/* Background cable */}
                <path d={pathD} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="2" />

                {/* Glowing packet stream */}
                <motion.path
                  d={pathD}
                  fill="none"
                  stroke={service.color}
                  strokeWidth="3"
                  strokeDasharray="4 30"
                  animate={{
                    strokeDashoffset: isActive ? [-100, 0] : [100, 0],
                  }}
                  transition={{
                    duration: isActive ? 1 : 3,
                    repeat: Infinity,
                    ease: 'linear',
                  }}
                  style={{
                    filter: `drop-shadow(0 0 8px ${service.color})`,
                  }}
                />
              </g>
            );
          })}
        </svg>

        {/* Central Hub (Core Data Center) */}
        <div
          className="absolute z-30 flex flex-col items-center justify-center w-40 h-40 rounded-3xl bg-[#0a0a1a] border border-indigo-500/50 shadow-[0_0_80px_rgba(99,102,241,0.4)]"
          style={{ transform: 'translate(-50%, -50%)', left: '50%', top: '50%' }}
        >
          <div className="absolute inset-0 rounded-3xl border-2 border-indigo-500/30 animate-ping opacity-20" />

          <Cpu className="w-16 h-16 text-indigo-400 mb-2" />
          <div className="flex gap-1 mb-2">
            {[1, 2, 3].map((i) => (
              <motion.div
                key={i}
                animate={{ opacity: [0.3, 1, 0.3] }}
                transition={{ duration: 1.5, repeat: Infinity, delay: i * 0.2 }}
                className="w-2 h-2 rounded-full bg-indigo-400 shadow-[0_0_5px_#818cf8]"
              />
            ))}
          </div>
          <span className="font-bold text-white text-sm tracking-widest">{copy.coreLabel}</span>
        </div>

        {/* Service Nodes */}
        {services.map((service) => {
          const isActive = activeService === service.id;
          const isFaded = activeService && !isActive;

          return (
            <div
              key={`node-${service.id}`}
              className="absolute z-40 transition-all duration-500"
              style={{
                transform: `translate(-50%, -50%)`,
                left: `calc(50% + ${service.x}px)`,
                top: `calc(50% + ${service.y}px)`,
                opacity: isFaded ? 0.4 : 1,
                scale: isActive ? 1.1 : isFaded ? 0.9 : 1,
              }}
              onMouseEnter={() => setActiveService(service.id)}
              onMouseLeave={() => setActiveService(null)}
            >
              <div className="relative group cursor-pointer">
                {/* Icon Container */}
                <div
                  className="relative flex items-center justify-center w-20 h-20 rounded-2xl bg-[#0f0f29] border-2 transition-all duration-300 overflow-hidden"
                  style={{
                    borderColor: isActive ? service.color : 'rgba(255,255,255,0.1)',
                    boxShadow: isActive ? `0 0 30px ${service.color}60` : `0 0 15px rgba(0,0,0,0.5)`,
                  }}
                >
                  {/* Hover gradient background inside the node */}
                  <div
                    className="absolute inset-0 opacity-0 group-hover:opacity-20 transition-opacity duration-300"
                    style={{ background: `radial-gradient(circle at center, ${service.color}, transparent)` }}
                  />
                  <service.icon
                    size={32}
                    className="transition-colors duration-300"
                    style={{ color: isActive ? '#fff' : service.color }}
                  />
                </div>

                {/* Floating Info Card (Shows on Hover/Active) */}
                <AnimatePresence>
                  {isActive && (
                    <motion.div
                      initial={{ opacity: 0, y: 10, scale: 0.95 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: 5, scale: 0.95 }}
                      transition={{ duration: 0.2 }}
                      className="absolute top-24 left-1/2 -translate-x-1/2 w-[300px] p-5 rounded-2xl bg-[#13132f]/95 backdrop-blur-xl border border-white/10 shadow-2xl z-50 pointer-events-none"
                    >
                      <h4 className="text-xl font-bold mb-2 text-white flex items-center gap-2">
                        <span
                          className="w-2 h-2 rounded-full"
                          style={{ backgroundColor: service.color, boxShadow: `0 0 10px ${service.color}` }}
                        />
                        {service.title}
                      </h4>
                      <p className="text-sm text-gray-400 mb-4 leading-relaxed">{service.desc}</p>

                      <div className="space-y-2 pt-3 border-t border-white/5">
                        {service.stats.map((stat, idx) => (
                          <div key={idx} className="flex justify-between items-center text-xs">
                            <span className="text-gray-500 font-mono">{stat.label}</span>
                            <span className="text-indigo-300 font-bold bg-indigo-500/10 px-2 py-1 rounded">
                              {stat.value}
                            </span>
                          </div>
                        ))}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>

                {/* Label (when not hovered) */}
                <div
                  className={`absolute -bottom-8 left-1/2 -translate-x-1/2 whitespace-nowrap text-sm font-medium transition-opacity duration-300 ${
                    isActive ? 'opacity-0' : 'opacity-100 text-gray-300'
                  }`}
                >
                  {service.title}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Decorative Server Rack Elements on the sides */}
      <div className="hidden lg:flex absolute right-4 top-1/2 -translate-y-1/2 flex-col gap-2 opacity-20 pointer-events-none">
        {[1, 2, 3, 4, 5].map((i) => (
          <div key={i} className="w-16 h-8 border border-white/20 rounded bg-white/5 flex items-center px-2 gap-1">
            <div
              className="w-1 h-1 rounded-full bg-green-500 animate-pulse"
              style={{ animationDelay: `${i * 0.3}s` }}
            />
            <div className="w-1 h-1 rounded-full bg-blue-500" />
          </div>
        ))}
      </div>
      <div className="hidden lg:flex absolute left-4 top-1/2 -translate-y-1/2 flex-col gap-2 opacity-20 pointer-events-none">
        {[1, 2, 3, 4, 5].map((i) => (
          <div
            key={i}
            className="w-16 h-8 border border-white/20 rounded bg-white/5 flex items-center justify-end px-2 gap-1"
          >
            <div
              className="w-1 h-1 rounded-full bg-green-500 animate-pulse"
              style={{ animationDelay: `${i * 0.5}s` }}
            />
            <div className="w-1 h-1 rounded-full bg-blue-500" />
          </div>
        ))}
      </div>
    </section>
  );
}
