import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { Search, X, Loader2, ArrowRight, FileText, Users, Briefcase, Layers } from "lucide-react";
import { searchAll } from "../lib/api";
import { SOLUTIONS } from "../data/solutions";
import { INDUSTRIES } from "../data/site";

const QUICK_LINKS = [
  { title: "Cybersecurity & Resilience", to: "/solutions/cybersecurity-resilience" },
  { title: "Data Centre & Continuity", to: "/solutions/data-centre-infrastructure" },
  { title: "Technology Partners", to: "/partners" },
  { title: "Careers", to: "/about/careers" },
];

/** Compact ⌘K search palette — anchored under the header, never a full-page takeover. */
export default function SearchOverlay({ open, onClose }) {
  const [q, setQ] = useState("");
  const [data, setData] = useState<Record<string, Record<string, any>[]> | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();
  const reduce = useReducedMotion();

  useEffect(() => {
    if (open) {
      setQ("");
      setData(null);
      setActiveIdx(0);
      setTimeout(() => inputRef.current?.focus(), 60);
      const esc = (e) => e.key === "Escape" && onClose();
      window.addEventListener("keydown", esc);
      return () => window.removeEventListener("keydown", esc);
    }
  }, [open, onClose]);

  useEffect(() => {
    if (q.trim().length < 2) { setData(null); return; }
    setLoading(true);
    const t = setTimeout(async () => {
      try {
        const d = await searchAll(q.trim());
        setData(d);
      } catch {
        setData({ partners: [], blog: [], jobs: [], case_studies: [] });
      }
      setLoading(false);
    }, 300);
    return () => clearTimeout(t);
  }, [q]);

  const term = q.trim().toLowerCase();
  const solutionHits = term.length >= 2
    ? SOLUTIONS.filter((s) =>
        (s.shortTitle + " " + s.services.join(" ")).toLowerCase().includes(term)
      ).slice(0, 4).map((s) => ({ title: s.shortTitle, to: `/solutions/${s.slug}`, sub: s.services.slice(0, 4).join(" • ") }))
    : [];
  const industryHits = term.length >= 2
    ? INDUSTRIES.filter((i) => i.name.toLowerCase().includes(term)).slice(0, 3).map((i) => ({ title: i.name, to: "/clients", sub: "Industry served" }))
    : [];
  const faqHits = term.length >= 2
    ? SOLUTIONS.flatMap((s) =>
        s.faqs.filter((f) => f.q.toLowerCase().includes(term) || f.a.toLowerCase().includes(term))
          .map((f) => ({ title: f.q, to: `/solutions/${s.slug}`, sub: `FAQ — ${s.shortTitle}` }))
      ).slice(0, 4)
    : [];

  const go = (to) => { onClose(); navigate(to); };

  const sections = [
    { label: "Solutions", items: solutionHits },
    { label: "FAQs", items: faqHits },
    { label: "Industries", items: industryHits },
    { label: "Partners", items: (data?.partners || []).map((p) => ({ title: p.name, to: `/partners/${p.slug}`, sub: p.category })) },
    { label: "Insights", items: (data?.blog || []).map((b) => ({ title: b.title, to: `/about/blog/${b.slug}`, sub: b.category })) },
    { label: "Careers", items: (data?.jobs || []).map((j) => ({ title: j.title, to: "/about/careers", sub: j.team })) },
  ].filter((s) => s.items.length > 0);

  const items = sections.flatMap((s) => s.items);

  /* Keyboard navigation: ↑/↓ move, Enter opens. */
  const onKey = (e: React.KeyboardEvent) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setActiveIdx((i) => Math.min(i + 1, Math.max(items.length - 1, 0))); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setActiveIdx((i) => Math.max(i - 1, 0)); }
    else if (e.key === "Enter" && items[activeIdx]) { go(items[activeIdx].to); }
  };

  useEffect(() => {
    setActiveIdx(0);
  }, [q]);

  useEffect(() => {
    document.querySelector('[data-active="true"]')?.scrollIntoView({ block: "nearest" });
  }, [activeIdx, q, data]);

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          key="search-root"
          initial={reduce ? { opacity: 1 } : { opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={reduce ? { opacity: 1 } : { opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="fixed inset-0 z-[90] bg-[#050B14]/60 backdrop-blur-sm flex items-start justify-center px-4 pt-20 sm:pt-24"
          onClick={onClose}
          data-testid="search-overlay"
        >
          <motion.div
            initial={reduce ? { opacity: 1 } : { opacity: 0, y: -16, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={reduce ? { opacity: 1 } : { opacity: 0, y: -10, scale: 0.985 }}
            transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
            className="w-full max-w-2xl bg-[#0F1116] backdrop-blur-2xl border border-white/12 shadow-[0_40px_90px_rgba(0,0,0,0.6)]"
            onClick={(e) => e.stopPropagation()}
            onKeyDown={onKey}
            role="dialog"
            aria-label="Site search"
          >
            {/* input row */}
            <div className="flex items-center gap-3 border-b border-white/10 px-5 py-3.5">
              <Search size={17} className="text-cy shrink-0" aria-hidden="true" />
              <input
                ref={inputRef}
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder="Search solutions, partners, insights, careers…"
                className="flex-1 bg-transparent text-[15px] font-semibold text-white placeholder:text-white/30 outline-none min-w-0"
                data-testid="search-input"
                aria-label="Search"
              />
              {loading && <Loader2 size={16} className="text-cy animate-spin shrink-0" aria-hidden="true" />}
              <button
                onClick={onClose}
                aria-label="Close search"
                className="h-8 w-8 grid place-items-center border border-white/15 text-white/60 hover:text-white hover:border-cy/50 transition-colors shrink-0"
                data-testid="search-close-button"
              >
                <X size={15} />
              </button>
            </div>

            {/* body */}
            <div className="max-h-[55vh] overflow-y-auto" data-lenis-prevent>
              {q.trim().length < 2 ? (
                <div className="px-5 py-5" data-testid="search-quick-links">
                  <p className="text-[9.5px] font-tech tracking-[0.25em] text-white/40 mb-3 flex items-center gap-2">
                    <span className="h-px w-4 bg-white/25 inline-block" /> QUICK LINKS
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {QUICK_LINKS.map((ql) => (
                      <button
                        key={ql.to}
                        onClick={() => go(ql.to)}
                        className="text-[12px] font-semibold border border-white/15 text-white/70 hover:text-cy hover:border-cy/50 px-3.5 py-2 transition-colors"
                        data-testid={`search-quick-${ql.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 30)}`}
                      >
                        {ql.title}
                      </button>
                    ))}
                  </div>
                  <p className="mt-4 text-[10px] font-tech tracking-[0.16em] text-white/30">TYPE TO SEARCH · ↑↓ TO NAVIGATE · ENTER TO OPEN</p>
                </div>
              ) : items.length === 0 && !loading ? (
                <p className="px-5 py-6 text-white/50 text-[13px]" data-testid="search-no-results">
                  No results for “{q}”. Try “cybersecurity”, “cloud” or a partner name.
                </p>
              ) : (
                <div className="py-2">
                  {(() => {
                    let gi = -1;
                    return sections.map((s) => (
                      <div key={s.label}>
                        <p className="px-5 pt-3 pb-1.5 text-[9.5px] font-tech tracking-[0.25em] text-cy/80 uppercase flex items-center gap-2">
                          <span className="h-px w-3 bg-cy/40 inline-block" /> {s.label}
                        </p>
                        {s.items.map((item, i) => {
                          gi += 1;
                          const activeRow = gi === activeIdx;
                          return (
                            <button
                              key={`${s.label}-${i}`}
                              onClick={() => go(item.to)}
                              className={`w-full flex items-center justify-between gap-4 px-5 py-2.5 text-left transition-colors border-l-2 ${
                                activeRow ? "bg-white/[0.07] border-cy" : "border-transparent hover:bg-white/[0.04]"
                              }`}
                              data-active={activeRow || undefined}
                              data-testid={`search-result-${s.label.toLowerCase()}-${i}`}
                            >
                              <span className="min-w-0">
                                <span className={`block font-display font-bold text-[13px] transition-colors ${activeRow ? "text-cy" : "text-white/85"}`}>{item.title}</span>
                                {item.sub && <span className="block text-[11px] text-white/40 mt-0.5 line-clamp-1">{item.sub}</span>}
                              </span>
                              <ArrowRight size={14} className={`shrink-0 transition-colors ${activeRow ? "text-ember" : "text-white/25"}`} />
                            </button>
                          );
                        })}
                      </div>
                    ));
                  })()}
                </div>
              )}
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
