import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { ArrowUpRight, RotateCcw, Compass, Building2, Target } from "lucide-react";
import Reveal from "./Reveal";
import { INDUSTRIES } from "../data/site";

interface Goal {
  label: string;
  slugs: string[];
}

const GOALS: Goal[] = [
  { label: "Protect the business & stay compliant", slugs: ["cybersecurity-resilience"] },
  { label: "Modernise our data centre & continuity", slugs: ["data-centre-infrastructure"] },
  { label: "Move to cloud & a digital workplace", slugs: ["cloud-digital-workplace"] },
  { label: "Connect offices, teams & meeting rooms", slugs: ["network-connectivity", "collaboration-av-iot"] },
  { label: "Build software & use data / AI", slugs: ["software-data-digital-engineering"] },
  { label: "Outsource IT operations & support", slugs: ["managed-it-technology-services"] },
];

const PRACTICES: Record<string, string> = {
  "data-centre-infrastructure": "Data Centre, Infrastructure & Continuity",
  "network-connectivity": "Networking, Wireless & Cabling",
  "cybersecurity-resilience": "Cybersecurity & Security Operations",
  "cloud-digital-workplace": "Cloud, Licensing & Digital Workplace",
  "collaboration-av-iot": "UC, AV, Security & IoT",
  "software-data-digital-engineering": "Software, Data & Digital Engineering",
  "managed-it-technology-services": "Managed IT & Technology Services",
};

/** NOC-terminal styled 2-step discovery: pick industry + priority, get matched practices. */
export default function SolutionFinder() {
  const [industry, setIndustry] = useState<string | null>(null);
  const [goal, setGoal] = useState<string | null>(null);
  const done = industry !== null && goal !== null;

  const results = useMemo(() => {
    if (!done) return [] as string[];
    const fromGoal = GOALS.find((g) => g.label === goal)?.slugs || [];
    const fromIndustry = INDUSTRIES.find((i) => i.name === industry)?.pillars || [];
    return [...new Set([...fromGoal, ...fromIndustry])].slice(0, 3);
  }, [done, industry, goal]);

  const reset = () => {
    setIndustry(null);
    setGoal(null);
  };

  return (
    <section className="relative bg-[#0A1F44] py-24 md:py-32 overflow-hidden border-t border-white/10" data-testid="solution-finder">
      {/* fiber-optic field under the terminal grid */}
      <div className="absolute inset-0" aria-hidden="true">
        <img src="/images/home/fiber-optic.jpg" alt="" loading="lazy" className="h-full w-full object-cover opacity-[0.16]" />
        <div className="absolute inset-0 bg-gradient-to-b from-[#0A1F44]/85 via-[#0A1F44]/92 to-[#0A1F44]" />
      </div>
      <div className="absolute inset-0 bg-grid-dark pointer-events-none" aria-hidden="true" />
      <div
        className="absolute inset-0 pointer-events-none opacity-60"
        aria-hidden="true"
        style={{ backgroundImage: "repeating-linear-gradient(0deg, rgba(0,194,209,0.035) 0px, rgba(0,194,209,0.035) 1px, transparent 1px, transparent 4px)" }}
      />
      <div className="absolute -top-32 -left-32 h-[420px] w-[420px] rounded-full bg-cy/10 blur-[130px] pointer-events-none" aria-hidden="true" />
      <div className="absolute -bottom-32 -right-32 h-[420px] w-[420px] rounded-full bg-ember/10 blur-[130px] pointer-events-none" aria-hidden="true" />

      <div className="mx-auto max-w-[1320px] px-5 md:px-10 relative">
        <Reveal>
          <p className="text-xs font-tech tracking-[0.35em] text-cy mb-5 flex items-center gap-3">
            <span className="h-px w-10 bg-cy/50 inline-block" />
            <Compass size={15} /> SOLUTION FINDER
          </p>
          <h2 className="font-display font-black text-3xl md:text-5xl text-white tracking-tight max-w-2xl">
            Where should we start?
          </h2>
          <p className="mt-4 text-sm text-white/60 max-w-xl leading-relaxed">
            Two quick questions and we&apos;ll point you to the right Aviokan practices for your situation.
          </p>
        </Reveal>

        <div className="mt-10 grid lg:grid-cols-2 gap-4">
          <Reveal delay={0.05}>
            <div className="relative h-full bg-[#07152E]/80 border border-cy/25 p-7 backdrop-blur-sm" data-testid="finder-step-industry">
              <span className="absolute -top-px -left-px h-3 w-3 border-t-2 border-l-2 border-cy" aria-hidden="true" />
              <span className="absolute -bottom-px -right-px h-3 w-3 border-b-2 border-r-2 border-cy" aria-hidden="true" />
              <p className="text-[11px] font-tech tracking-[0.22em] text-cy flex items-center gap-2 mb-5">
                <Building2 size={13} /> STEP 1 — YOUR INDUSTRY
              </p>
              <div className="flex flex-wrap gap-2">
                {INDUSTRIES.map((i) => (
                  <button
                    key={i.name}
                    onClick={() => setIndustry(i.name)}
                    className={`text-[12px] font-bold px-3.5 py-2 border transition-colors duration-200 ${
                      industry === i.name
                        ? "bg-cy text-[#0A1F44] border-cy"
                        : "border-white/15 text-white/65 hover:text-white hover:border-cy/60"
                    }`}
                    data-testid={`finder-industry-${i.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`}
                  >
                    {i.name}
                  </button>
                ))}
              </div>
            </div>
          </Reveal>
          <Reveal delay={0.1}>
            <div className="relative h-full bg-[#07152E]/80 border border-ember/30 p-7 backdrop-blur-sm" data-testid="finder-step-goal">
              <span className="absolute -top-px -left-px h-3 w-3 border-t-2 border-l-2 border-ember" aria-hidden="true" />
              <span className="absolute -bottom-px -right-px h-3 w-3 border-b-2 border-r-2 border-ember" aria-hidden="true" />
              <p className="text-[11px] font-tech tracking-[0.22em] text-ember flex items-center gap-2 mb-5">
                <Target size={13} /> STEP 2 — YOUR PRIORITY RIGHT NOW
              </p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {GOALS.map((g) => (
                  <button
                    key={g.label}
                    onClick={() => setGoal(g.label)}
                    className={`text-[12px] font-bold px-3.5 py-2.5 border text-left transition-colors duration-200 ${
                      goal === g.label
                        ? "bg-ember text-white border-ember"
                        : "border-white/15 text-white/65 hover:text-white hover:border-ember/60"
                    }`}
                    data-testid={`finder-goal-${g.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40)}`}
                  >
                    {g.label}
                  </button>
                ))}
              </div>
            </div>
          </Reveal>
        </div>

        <Reveal delay={0.12}>
          <div
            className={`mt-4 relative border p-7 transition-colors duration-300 ${
              done ? "bg-[#07152E]/90 border-cy/50 shadow-[0_0_44px_-10px_rgba(0,194,209,0.35)]" : "bg-white/[0.03] border-dashed border-white/20"
            }`}
            data-testid="finder-result"
          >
            {done ? (
              <div>
                <div className="flex items-start justify-between gap-4 flex-wrap">
                  <div>
                    <p className="text-[11px] font-tech tracking-[0.25em] text-cy flex items-center gap-2">
                      <span className="h-1.5 w-1.5 rounded-full bg-cy animate-pulse inline-block" />
                      RECOMMENDED FOR YOU
                    </p>
                    <p className="text-sm text-white/60 mt-2">
                      {industry} · {goal}
                    </p>
                  </div>
                  <button
                    onClick={reset}
                    className="text-[12px] font-bold text-white/60 hover:text-cy transition-colors flex items-center gap-1.5"
                    data-testid="finder-reset"
                  >
                    <RotateCcw size={13} /> Start over
                  </button>
                </div>
                <div className="grid md:grid-cols-3 gap-3 mt-6">
                  {results.map((slug, i) => (
                    <Link
                      key={slug}
                      to={`/solutions/${slug}`}
                      className="group flex items-center justify-between gap-3 border border-white/15 bg-white/5 hover:bg-white/10 hover:border-cy/50 px-5 py-4 transition-colors duration-300"
                      data-testid={`finder-result-${slug}`}
                    >
                      <span>
                        <span className="block font-tech text-[10px] text-ember">{String(i + 1).padStart(2, "0")}</span>
                        <span className="block font-display font-bold text-white text-sm mt-1">{PRACTICES[slug]}</span>
                      </span>
                      <ArrowUpRight size={16} className="text-cy shrink-0 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform" />
                    </Link>
                  ))}
                </div>
                <p className="mt-5 text-xs text-white/50">
                  Want a guided assessment instead?{" "}
                  <Link to="/contact" className="text-cy hover:text-white transition-colors font-bold">
                    Talk to an Aviokan consultant →
                  </Link>
                </p>
              </div>
            ) : (
              <p className="text-sm text-white/45 font-tech tracking-wide">
                {industry ? "NOW PICK YOUR CURRENT PRIORITY —" : "PICK YOUR INDUSTRY TO BEGIN —"} YOUR MATCHED PRACTICES WILL APPEAR HERE.
              </p>
            )}
          </div>
        </Reveal>
      </div>
    </section>
  );
}
