import { useEffect, useState } from "react";
import { useReducedMotion } from "framer-motion";
import { Activity, ShieldAlert, MonitorSmartphone, ShieldCheck } from "lucide-react";

// Stylised NOC console — a self-demonstrating illustration of Aviokan's managed
// operations posture. Values cycle locally for effect; the caption marks it as a simulation.
const LOG_POOL: { tag: string; text: string; cls: string }[] = [
  { tag: "FW", text: "FW-HQ-01 · policy sync OK · 0 violations", cls: "text-cy" },
  { tag: "SOC", text: "alert triaged · benign · auto-closed", cls: "text-white/70" },
  { tag: "BKP", text: "BKP-DC1 · nightly verification PASS", cls: "text-cy" },
  { tag: "NET", text: "SD-WAN edge · failover state healthy", cls: "text-white/70" },
  { tag: "DC", text: "precision cooling · inlet 22.4°C · nominal", cls: "text-white/70" },
  { tag: "IAM", text: "MFA challenge surge · 0 escalations", cls: "text-cy" },
  { tag: "OPS", text: "patch wave 7/12 · fleet compliant", cls: "text-ember" },
  { tag: "WIFI", text: "campus heatmap · coverage validated", cls: "text-white/70" },
  { tag: "DR", text: "replication lag 1.2s · within RPO", cls: "text-cy" },
  { tag: "PWR", text: "UPS-A load 62% · batteries GREEN", cls: "text-white/70" },
];

const clock = () => new Date().toLocaleTimeString("en-GB", { hour12: false });

export default function OpsConsole() {
  const reduce = useReducedMotion();
  const [time, setTime] = useState(clock());
  const [uptime, setUptime] = useState("99.98");
  const [threats, setThreats] = useState(12480);
  const [endpoints, setEndpoints] = useState(1284);
  const [lines, setLines] = useState(() => LOG_POOL.slice(0, 4).map((l) => ({ ...l, ts: clock() })));

  useEffect(() => {
    if (reduce) return;
    const t = setInterval(() => setTime(clock()), 1000);
    return () => clearInterval(t);
  }, [reduce]);

  useEffect(() => {
    if (reduce) return;
    const t = setInterval(() => {
      setThreats((v) => v + 1 + Math.floor(Math.random() * 7));
      if (Math.random() > 0.6) setUptime((Math.random() * 0.04 + 99.95).toFixed(2));
      if (Math.random() > 0.7) setEndpoints((v) => Math.max(1200, v + (Math.random() > 0.5 ? 1 : -1) * Math.ceil(Math.random() * 4)));
      setLines((prev) => {
        const next = { ...LOG_POOL[Math.floor(Math.random() * LOG_POOL.length)], ts: clock() };
        return [...prev.slice(-3), next];
      });
    }, 2200);
    return () => clearInterval(t);
  }, [reduce]);

  const tiles = [
    { icon: Activity, label: "MANAGED UPTIME", value: `${uptime}%`, cls: "text-cy", testId: "ops-uptime" },
    { icon: ShieldAlert, label: "THREATS DEFLECTED", value: threats.toLocaleString("en-IN"), cls: "text-ember", testId: "ops-threats" },
    { icon: MonitorSmartphone, label: "ENDPOINTS MONITORED", value: endpoints.toLocaleString("en-IN"), cls: "text-white", testId: "ops-endpoints" },
    { icon: ShieldCheck, label: "SECURITY POSTURE", value: "24×7", cls: "text-cy", testId: "ops-posture" },
  ];

  return (
    <div className="relative" data-testid="ops-console">
      {/* Console frame */}
      <div className="relative rounded-sm border border-white/15 bg-[#0B0C10]/70 backdrop-blur-xl overflow-hidden">
        {/* HUD corner brackets */}
        <span className="pointer-events-none absolute top-0 left-0 h-4 w-4 border-t-2 border-l-2 border-cy/80 z-10" aria-hidden="true" />
        <span className="pointer-events-none absolute top-0 right-0 h-4 w-4 border-t-2 border-r-2 border-cy/80 z-10" aria-hidden="true" />
        <span className="pointer-events-none absolute bottom-0 left-0 h-4 w-4 border-b-2 border-l-2 border-cy/80 z-10" aria-hidden="true" />
        <span className="pointer-events-none absolute bottom-0 right-0 h-4 w-4 border-b-2 border-r-2 border-cy/80 z-10" aria-hidden="true" />
        {/* Title bar */}
        <div className="flex items-center justify-between gap-3 border-b border-white/10 px-4 py-2.5 bg-white/[0.04]">
          <div className="flex items-center gap-2.5 min-w-0">
            <span className="h-2 w-2 rounded-full bg-ember shrink-0 animate-pulse" aria-hidden="true" />
            <span className="font-tech text-[10px] sm:text-[11px] tracking-[0.22em] text-white/80 truncate">
              AVIOKAN // NETWORK OPERATIONS
            </span>
          </div>
          <span className="font-tech text-[10px] sm:text-[11px] text-cy tabular-nums shrink-0" data-testid="ops-clock">{time}</span>
        </div>

        {/* Stat tiles */}
        <div className="grid grid-cols-2 gap-px bg-white/10">
          {tiles.map((t) => (
            <div key={t.label} className="bg-[#101218]/90 px-4 py-4" data-testid={t.testId}>
              <div className="flex items-center gap-1.5">
                <t.icon size={11} className="text-white/40" aria-hidden="true" />
                <p className="font-tech text-[9px] tracking-[0.18em] text-white/45">{t.label}</p>
              </div>
              <p className={`font-tech text-xl sm:text-2xl mt-1.5 tabular-nums tracking-tight ${t.cls}`}>{t.value}</p>
            </div>
          ))}
        </div>

        {/* Event log */}
        <div className="px-4 py-3.5 bg-[#0B0C10]/95">
          <p className="font-tech text-[9px] tracking-[0.22em] text-white/40 mb-2.5 flex items-center justify-between">
            <span>LIVE EVENT STREAM</span>
            <span className="text-cy/70">/var/log/aviokan</span>
          </p>
          <div className="space-y-1.5 min-h-[104px]" data-testid="ops-log">
            {lines.map((l, i) => (
              <p key={`${l.tag}-${i}-${l.text}`} className={`font-tech text-[10px] leading-relaxed ops-line ${i === lines.length - 1 ? "opacity-100" : "opacity-55"}`}>
                <span className="text-white/35">[{l.ts}]</span> <span className={`${l.cls} font-bold`}>{l.tag}</span>
                <span className="text-white/60"> {l.text}</span>
              </p>
            ))}
            <p className="font-tech text-[10px] text-cy">
              <span className="ops-cursor">▍</span>
            </p>
          </div>
        </div>

        {/* Scanline */}
        <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden="true">
          <div className="ops-scan absolute left-0 right-0 h-px bg-gradient-to-r from-transparent via-cy/25 to-transparent" />
        </div>
      </div>

      <p className="mt-3 text-center font-tech text-[9px] tracking-[0.24em] text-white/35">
        SIMULATED VIEW · REPRESENTATIVE OF AVIOKAN MANAGED ENVIRONMENTS
      </p>
    </div>
  );
}
