"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { 
  Wifi, 
  RefreshCw,
  MapPin,
  Activity,
  CheckCircle2
} from "lucide-react";
import { cn } from "@/lib/utils";
import { DottedMap } from "@/components/ui/dotted-map";
import Flag from "react-flagkit";
import { siteConfig } from "@/lib/config/site";

const locations = siteConfig.locations;
type Location = (typeof locations)[number];

const getPingColor    = (p: number) => p < 50 ? "bg-emerald-500" : p < 150 ? "bg-amber-500" : "bg-rose-500";
const getPingTextColor = (p: number) => p < 50 ? "text-emerald-400" : p < 150 ? "text-amber-400" : "text-rose-400";
const getPingStatus   = (p: number) => p < 50 ? "Excellent" : p < 150 ? "Good" : "Fair";
const getPingBg       = (p: number) => p < 50 ? "bg-emerald-500/10 border-emerald-500/20" : p < 150 ? "bg-amber-500/10 border-amber-500/20" : "bg-rose-500/10 border-rose-500/20";

const MapMarker = ({
  location,
  ping,
  isHovered,
  onHover,
}: {
  location: Location;
  ping?: number;
  isHovered: boolean;
  onHover: (id: string | null) => void;
}) => (
  <div
    className="absolute"
    style={{
      left: `${location.coordinates.x}%`,
      top: `${location.coordinates.y}%`,
      transform: "translate(-50%, -50%)",
      zIndex: isHovered ? 50 : 10,
    }}
    onMouseEnter={() => onHover(location.id)}
    onMouseLeave={() => onHover(null)}
  >
    <motion.div
      animate={{ scale: [1, 1.8], opacity: [0.5, 0] }}
      transition={{ duration: 2.2, repeat: Infinity, ease: "easeOut" }}
      className="absolute inset-0 w-4 h-4 rounded-full bg-accent-hover/30"
      style={{ top: "50%", left: "15%", transform: "translate(-50%, -50%)" }}
    />

    <motion.div
      whileHover={{ scale: 1.3 }}
      className="relative w-6 h-6 rounded-full bg-accent cursor-pointer flex items-center justify-center border border-border"
    >
      <div className="w-1 h-1 rounded-full bg-white" />
    </motion.div>

    <AnimatePresence>
      {isHovered && (
        <motion.div
          initial={{ opacity: 0, scale: 0.85, y: 8 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.85, y: 8 }}
          transition={{ duration: 0.18 }}
          className="absolute top-full mt-3 left-1/2 -translate-x-1/2 z-50 whitespace-nowrap hidden sm:block"
        >
          <div className="bg-surface rounded-2xl px-4 py-3 border border-white/8 space-y-3 min-w-[220px]">
            <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-0.5">
              <div className="w-2 h-2 bg-surface rotate-45 border-l border-t border-white/8" />
            </div>

            <div className="flex items-center gap-2.5">
              <Flag country={location.countryCode} size={20} />
              <div>
                <p className="text-sm font-semibold text-content leading-none">{location.fullName}</p>
                <p className="text-xs text-content-muted mt-0.5">Server Location</p>
              </div>
            </div>

            <div className="h-px bg-zinc-800/80" />

            {ping !== undefined ? (
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className={cn("p-1.5 rounded-lg", getPingColor(ping))}>
                    <Activity className="w-3 h-3 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-content-muted">Latency</p>
                    <p className={cn("text-sm font-bold", getPingTextColor(ping))}>{ping}ms</p>
                  </div>
                </div>
                <span className={cn("text-xs font-semibold px-2.5 py-1 rounded-lg border", getPingBg(ping), getPingTextColor(ping))}>
                  {getPingStatus(ping)}
                </span>
              </div>
            ) : (
              <p className="text-xs text-content-subtle text-center">Run ping test to see latency</p>
            )}
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  </div>
);

const ConnectionLine = ({
  from,
  to,
  isPinging,
}: {
  from: Location;
  to: Location;
  isPinging: boolean;
}) => (
  <motion.line
    x1={`${from.coordinates.x}%`}
    y1={`${from.coordinates.y}%`}
    x2={`${to.coordinates.x}%`}
    y2={`${to.coordinates.y}%`}
    stroke="rgba(139, 92, 246, 0.35)"
    strokeWidth="1.5"
    strokeDasharray={isPinging ? "8,5" : "0,0"}
    initial={{ strokeDashoffset: 0 }}
    animate={isPinging ? { strokeDashoffset: -13 } : { strokeDashoffset: 0 }}
    transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
    style={{ pointerEvents: "none" }}
  />
);

export default function LocationSection() {
  const [pingResults, setPingResults] = useState<Record<string, number>>({});
  const [isPinging, setIsPinging]     = useState(false);
  const [hoveredLocation, setHoveredLocation] = useState<string | null>(null);

  const measurePing = async (url: string) => {
    const start = performance.now();
    try { await fetch(url, { mode: "no-cors", cache: "no-store" }); } catch (_) {}
    return Math.floor(performance.now() - start);
  };

  const handlePingTest = async () => {
    setIsPinging(true);
    setPingResults({});
    const results: Record<string, number> = {};
    await Promise.all(locations.map(async (loc) => {
      results[loc.id] = await measurePing(loc.pingUrl);
    }));
    setPingResults(results);
    setIsPinging(false);
  };

  const getBestLocation = () => {
    if (Object.keys(pingResults).length === 0) return null;
    let best: Location = locations[0];
    let minPing = Infinity;
    locations.forEach((loc) => {
      if (pingResults[loc.id] && pingResults[loc.id] < minPing) {
        minPing = pingResults[loc.id];
        best = loc;
      }
    });
    return best;
  };

  const bestLocation = getBestLocation();

  return (
    <section
      className="relative w-full py-24 md:py-32 px-6 lg:px-12 font-sans overflow-hidden border-t border-border/80"
    >
      <div
        className="absolute inset-0 opacity-[0.025] pointer-events-none z-0"
        style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
          backgroundSize: "128px 128px",
        }}
      />

      <div className="relative z-10 max-w-7xl mx-auto">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
          className="mb-16 md:mb-20"
        >
          <div className="flex items-center gap-3 mb-6">
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
            <p className="text-xs font-bold text-accent-text uppercase tracking-widest">Global Infrastructure</p>
          </div>
          <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-white leading-tight mb-4">
            Servers Around the{" "}
            <span className="text-accent-text">
              World
            </span>
          </h2>
          <p className="text-lg text-content-dim max-w-xl">
            Connect to the nearest server for optimal performance, wherever your players are located.
          </p>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6 }}
            className="lg:col-span-2"
          >
            <div className="relative w-full aspect-video rounded-2xl overflow-hidden border border-white/6 bg-surface">
              <div className="absolute inset-0 opacity-50">
                <DottedMap />
              </div>

              <div className="absolute inset-0 pointer-events-none"
                style={{
                  background: `radial-gradient(ellipse 100% 100% at 50% 50%, transparent 55%, var(--bg-surface) 100%)`,
                }}
              />

              <svg className="absolute inset-0 w-full h-full" style={{ zIndex: 5 }}>
                {isPinging && (
                  <>
                    <ConnectionLine from={locations[0]} to={locations[1]} isPinging={isPinging} />
                    <ConnectionLine from={locations[1]} to={locations[2]} isPinging={isPinging} />
                    <ConnectionLine from={locations[0]} to={locations[3]} isPinging={isPinging} />
                    <ConnectionLine from={locations[3]} to={locations[1]} isPinging={isPinging} />
                  </>
                )}
              </svg>

              {locations.map((loc) => (
                <MapMarker
                  key={loc.id}
                  location={loc}
                  ping={pingResults[loc.id]}
                  isHovered={hoveredLocation === loc.id}
                  onHover={setHoveredLocation}
                />
              ))}

              <div className="absolute top-4 left-4 z-20 flex items-center gap-2 px-3 py-1.5 rounded-full border border-white/8 bg-surface/80 backdrop-blur-md">
                <motion.span
                  animate={{ opacity: [1, 0.4, 1] }}
                  transition={{ duration: 2, repeat: Infinity }}
                  className="w-1.5 h-1.5 rounded-full bg-accent-text"
                />
                <span className="text-xs font-medium text-content-dim">Live Network</span>
              </div>
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, x: 16 }}
            whileInView={{ opacity: 1, x: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6, delay: 0.1 }}
            className="lg:col-span-1 flex flex-col gap-2.5"
          >
            {locations.map((loc, i) => {
              const ping    = pingResults[loc.id];
              const isBest  = bestLocation?.id === loc.id;
              const isHov   = hoveredLocation === loc.id;

              return (
                <motion.div
                  key={loc.id}
                  initial={{ opacity: 0, y: 10 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.4, delay: i * 0.07 }}
                  onMouseEnter={() => setHoveredLocation(loc.id)}
                  onMouseLeave={() => setHoveredLocation(null)}
                  className={cn(
                    "relative p-4 rounded-xl border transition-colors duration-300 cursor-pointer overflow-hidden",
                    isHov
                      ? "border-accent-hover/50 bg-elevated"
                      : "border-white/6 bg-white/2 hover:border-white/10 hover:bg-white/4"
                  )}
                >
                  {isBest && (
                    <div className="absolute inset-0 pointer-events-none rounded-xl border border-accent-hover/30 bg-accent-hover/5" />
                  )}

                  <div className="flex items-center justify-between relative z-10">
                    <div className="flex items-center gap-3 flex-1 min-w-0">
                      <Flag country={loc.countryCode} size={20} />
                      <div className="min-w-0">
                        <div className="flex items-center gap-1.5">
                          <p className="text-sm font-semibold text-white truncate">{loc.name}</p>
                          {isBest && (
                            <CheckCircle2 className="w-3.5 h-3.5 text-accent-text shrink-0" />
                          )}
                        </div>
                        <p className="text-xs text-content-muted truncate">{loc.region}</p>
                      </div>
                    </div>

                    {ping !== undefined ? (
                      <motion.div
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: 1 }}
                        className="text-right shrink-0 ml-3"
                      >
                        <p className={cn("text-sm font-bold", getPingTextColor(ping))}>
                          {ping}ms
                        </p>
                        <p className="text-[10px] text-content-muted">{getPingStatus(ping)}</p>
                      </motion.div>
                    ) : (
                      <Wifi className={cn(
                        "w-4 h-4 shrink-0 ml-3 transition-colors",
                        isHov ? "text-accent-text/60" : "text-content-subtle"
                      )} />
                    )}
                  </div>

                  {ping !== undefined && (
                    <motion.div
                      initial={{ scaleX: 0 }}
                      animate={{ scaleX: 1 }}
                      transition={{ duration: 0.5, delay: 0.1 }}
                      className={`mt-3 h-px rounded-full origin-left ${ping < 50 ? "bg-emerald-500/40" : ping < 150 ? "bg-amber-500/40" : "bg-rose-500/40"}`}
                    />
                  )}
                </motion.div>
              );
            })}

            <motion.button
              initial={{ opacity: 0, y: 10 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.4, delay: 0.3 }}
              onClick={handlePingTest}
              disabled={isPinging}
              className={cn(
                "w-full mt-1 flex items-center justify-center gap-2 px-6 py-3 rounded-xl text-sm font-semibold transition-all duration-150 border",
                isPinging
                  ? "text-slate-500 border-white/6 bg-white/2 cursor-not-allowed"
                  : "text-white border-transparent bg-accent hover:bg-accent-hover shadow-[0_4px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:shadow-[0_6px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)]"
              )}
            >
              {isPinging ? (
                <>
                  <RefreshCw className="w-4 h-4 animate-spin" />
                  Testing connections…
                </>
              ) : (
                <>
                  <MapPin className="w-4 h-4" />
                  Test Connection
                </>
              )}
            </motion.button>
          </motion.div>
        </div>

        <AnimatePresence>
          {!isPinging && Object.keys(pingResults).length > 0 && (
            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 16 }}
              transition={{ duration: 0.4 }}
              className="mt-10 flex flex-col sm:flex-row items-center justify-center gap-3 text-center"
            >
              <p className="text-content-muted text-sm">Results updated · Hover markers for details</p>
              {bestLocation && (
                <>
                  <span className="hidden sm:block text-content-faint">·</span>
                  <p className="text-sm text-white">
                    Best for you:{" "}
                    <span className="font-semibold text-accent-text">
                      {bestLocation.fullName}
                    </span>
                  </p>
                </>
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </section>
  );
}