import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import SiteLayout from "@/components/SiteLayout";
import AnimateIn from "@/components/AnimateIn";
import FAQSection, { type FAQItem } from "@/components/FAQSection";
import {
  Sparkles,
  ArrowRight,
  Phone,
  MessageSquare,
  BookOpen,
  Server,
  Mail,
  CreditCard,
  ShieldCheck,
  Globe,
  Zap,
  Search,
  X,
  SearchX,
} from "lucide-react";

/**
 * Standalone FAQ page for DoItEasy.
 * Dark-premium hero (matches Service Catalog) followed by grouped FAQ sections
 * on a white background, then a light CTA to Knowledge Base / Contact.
 */

const GENERAL_FAQ: FAQItem[] = [
  {
    question: "What services does DoItEasy offer?",
    answer:
      "We provide enterprise-grade cloud VPS, dedicated servers, web hosting, business email (Bizmail360), WhatsApp API, Dedicated Internet Access (DIA), security services, and a full public API for automation. Everything is engineered around reliability, performance, and expert 24/7 support.",
  },
  {
    question: "Do you offer a service-level agreement (SLA)?",
    answer:
      "Yes. All infrastructure services are backed by a 99.99% uptime SLA. DIA and enterprise plans include additional guarantees around latency and mean time to response. Full SLA terms are available in your client portal under Service Terms.",
  },
  {
    question: "Where are your data centers located?",
    answer:
      "DoItEasy operates across multiple global regions with redundant interconnects. Customers can select their preferred region during provisioning to minimize latency and meet data residency requirements. Contact sales for a full current list.",
  },
  {
    question: "How does billing work?",
    answer:
      "You're billed monthly or annually depending on the plan you choose. Annual subscriptions receive a discount. Invoices are delivered through the client portal and can be paid via credit card, bank transfer, or supported payment gateways. Upgrades are prorated automatically.",
  },
];

const TECHNICAL_FAQ: FAQItem[] = [
  {
    question: "How fast is service provisioning?",
    answer:
      "Most cloud VPS and hosting products are provisioned automatically within minutes. Dedicated servers and custom network designs (DIA, colocation) typically take 1–3 business days depending on hardware and location.",
  },
  {
    question: "Can I migrate from my current provider?",
    answer:
      "Absolutely. Our migration team handles end-to-end moves for websites, email, databases, and full server environments — including DNS cutover planning and rollback. Standard migrations are free for most plans; complex migrations are scoped as a one-time service.",
  },
  {
    question: "Do you provide full root / administrator access?",
    answer:
      "Yes. Every VPS and dedicated server ships with full root (Linux) or administrator (Windows) access. You have complete control over the operating system, networking, firewall, and installed applications.",
  },
  {
    question: "What security measures protect my services?",
    answer:
      "Every product runs behind enterprise-grade firewalls, DDoS mitigation, and 24/7 monitoring. Optional add-ons include managed backups, malware scanning, SSL certificates, and compliance-ready configurations (ISO-aligned, GDPR, PCI).",
  },
];

const SUPPORT_FAQ: FAQItem[] = [
  {
    question: "How do I get help when I need it?",
    answer:
      "Our support team is available 24/7 via live chat, the client portal ticket system, and phone for priority accounts. Most tickets receive a first response within 15 minutes. We also offer a searchable Knowledge Base and video tutorials.",
  },
  {
    question: "Do you offer managed services?",
    answer:
      "Yes. Managed add-ons cover OS updates, security patching, proactive monitoring, performance tuning, backup management, and incident response. You can add them to any VPS or dedicated server plan.",
  },
  {
    question: "Is there a refund or money-back guarantee?",
    answer:
      "Most shared hosting and VPS plans come with a 7-day money-back guarantee. Dedicated resources, domain registrations, SSL certificates, and licenses are non-refundable once provisioned. Full details are in our Refund Policy.",
  },
];

type FAQGroup = {
  id: string;
  eyebrow: string;
  title: string;
  subtitle: string;
  items: FAQItem[];
  bg?: string;
};

export default function FAQ() {
  const [query, setQuery] = useState("");

  const groups: FAQGroup[] = [
    {
      id: "faq-general",
      eyebrow: "General",
      title: "General Questions",
      subtitle:
        "The fundamentals: what we offer, where we operate, and how billing works.",
      items: GENERAL_FAQ,
    },
    {
      id: "faq-technical",
      eyebrow: "Technical",
      title: "Technical Questions",
      subtitle:
        "Provisioning times, migrations, access, and security — answered.",
      items: TECHNICAL_FAQ,
      bg: "bg-slate-50/60",
    },
    {
      id: "faq-support",
      eyebrow: "Support",
      title: "Support & Services",
      subtitle:
        "How to reach our team, managed add-ons, and refund guarantees.",
      items: SUPPORT_FAQ,
    },
  ];

  const normalized = query.trim().toLowerCase();
  const isSearching = normalized.length > 0;

  const filteredGroups = useMemo(() => {
    if (!isSearching) return groups;
    return groups
      .map((g) => ({
        ...g,
        items: g.items.filter(
          (it) =>
            it.question.toLowerCase().includes(normalized) ||
            it.answer.toLowerCase().includes(normalized),
        ),
      }))
      .filter((g) => g.items.length > 0);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [normalized, isSearching]);

  const totalMatches = filteredGroups.reduce((n, g) => n + g.items.length, 0);

  return (
    <SiteLayout>
      {/* ================================================================ */}
      {/* HERO                                                             */}
      {/* ================================================================ */}
      <section className="relative overflow-hidden bg-black text-white">
        <div
          aria-hidden="true"
          className="absolute inset-0 bg-gradient-to-br from-[#031a05] via-black to-[#05130a]"
        />
        <div
          aria-hidden="true"
          className="absolute -top-40 -left-40 w-[520px] h-[520px] rounded-full bg-[#0e6305]/30 blur-[140px]"
        />
        <div
          aria-hidden="true"
          className="absolute top-1/3 -right-40 w-[480px] h-[480px] rounded-full bg-[#d4af37]/10 blur-[140px]"
        />
        <div
          aria-hidden="true"
          className="absolute inset-0 opacity-[0.06]"
          style={{
            backgroundImage:
              "linear-gradient(rgba(212,175,55,0.5) 1px, transparent 1px), linear-gradient(90deg, rgba(212,175,55,0.5) 1px, transparent 1px)",
            backgroundSize: "52px 52px",
          }}
        />

        <div className="relative max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28 text-center">
          <AnimateIn>
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#d4af37]/40 bg-[#d4af37]/5 text-[#f0d674] text-xs font-bold uppercase tracking-widest mb-6">
              <Sparkles className="w-3.5 h-3.5" />
              Help & Answers
            </div>
            <h1 className="text-4xl sm:text-5xl md:text-6xl font-black leading-[1.05] tracking-tight">
              Frequently Asked{" "}
              <span className="bg-gradient-to-r from-[#22c55e] via-[#0e6305] to-[#d4af37] bg-clip-text text-transparent">
                Questions
              </span>
            </h1>
            <p className="mt-6 text-lg md:text-xl text-slate-300/90 max-w-3xl mx-auto leading-relaxed">
              Answers to the most common questions about billing, provisioning,
              support, migrations, and the technology that powers DoItEasy.
            </p>

            <div className="mt-10 flex flex-wrap gap-3 justify-center">
              <a
                href="#faq-general"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-[#0e6305] hover:bg-[#0a4a04] text-white font-bold text-sm uppercase tracking-wider shadow-lg shadow-[#0e6305]/30 transition-all hover:-translate-y-0.5"
              >
                Browse FAQs
                <ArrowRight className="w-4 h-4" />
              </a>
              <Link
                to="/knowledge-base"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-white/5 hover:bg-white/10 border border-white/20 hover:border-[#d4af37]/60 text-white font-bold text-sm uppercase tracking-wider transition-all hover:-translate-y-0.5"
              >
                <BookOpen className="w-4 h-4" />
                Knowledge Base
              </Link>
            </div>
          </AnimateIn>
        </div>
        <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-b from-transparent to-white pointer-events-none" />
      </section>

      {/* ================================================================ */}
      {/* SEARCH BAR + CATEGORY CHIPS                                      */}
      {/* ================================================================ */}
      <section className="bg-white pt-14 pb-6">
        <div className="max-w-3xl mx-auto px-4 sm:px-6">
          <AnimateIn>
            <div className="relative group">
              <div
                aria-hidden="true"
                className="absolute -inset-[2px] rounded-2xl bg-gradient-to-r from-[#0e6305] via-[#22c55e] to-[#d4af37] opacity-20 group-focus-within:opacity-60 blur-md transition"
              />
              <div className="relative flex items-center gap-3 bg-white border-2 border-slate-200 group-focus-within:border-[#0e6305] rounded-2xl shadow-sm transition-all px-4 sm:px-5 py-3">
                <Search className="w-5 h-5 text-slate-400 group-focus-within:text-[#0e6305] shrink-0 transition" />
                <input
                  type="search"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Search FAQs — try “refund”, “uptime”, or “migration”…"
                  aria-label="Search frequently asked questions"
                  className="flex-1 bg-transparent outline-none text-slate-900 placeholder:text-slate-400 text-base py-1.5"
                />
                {isSearching && (
                  <button
                    type="button"
                    onClick={() => setQuery("")}
                    aria-label="Clear search"
                    className="shrink-0 w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 flex items-center justify-center transition"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>

            {/* Live result counter */}
            <div className="min-h-[24px] mt-3 flex items-center justify-center text-sm">
              {isSearching ? (
                totalMatches > 0 ? (
                  <span className="text-slate-600">
                    <span className="font-bold text-[#0e6305]">
                      {totalMatches}
                    </span>{" "}
                    result{totalMatches === 1 ? "" : "s"} for{" "}
                    <span className="font-semibold text-slate-900">
                      “{query.trim()}”
                    </span>
                  </span>
                ) : (
                  <span className="text-slate-500">
                    No results for{" "}
                    <span className="font-semibold text-slate-700">
                      “{query.trim()}”
                    </span>
                  </span>
                )
              ) : (
                <span className="text-slate-400">
                  Can’t find it? Try a different keyword or contact support.
                </span>
              )}
            </div>
          </AnimateIn>

          {/* Category chips — hidden while searching for a cleaner focus */}
          {!isSearching && (
            <AnimateIn>
              <div className="mt-8 grid grid-cols-2 md:grid-cols-4 gap-3">
                {[
                  { icon: Globe, label: "General", href: "#faq-general" },
                  { icon: Server, label: "Technical", href: "#faq-technical" },
                  {
                    icon: MessageSquare,
                    label: "Support",
                    href: "#faq-support",
                  },
                  {
                    icon: CreditCard,
                    label: "Billing",
                    href: "#faq-general",
                  },
                ].map((c) => {
                  const Icon = c.icon;
                  return (
                    <a
                      key={c.label}
                      href={c.href}
                      className="group flex items-center gap-3 px-4 py-3 rounded-xl border border-slate-200 hover:border-[#0e6305]/40 bg-white hover:shadow-md transition"
                    >
                      <span className="w-9 h-9 rounded-lg bg-[#0e6305]/10 text-[#0e6305] flex items-center justify-center group-hover:bg-[#0e6305] group-hover:text-white transition">
                        <Icon className="w-4 h-4" />
                      </span>
                      <span className="text-sm font-bold text-slate-800">
                        {c.label}
                      </span>
                    </a>
                  );
                })}
              </div>
            </AnimateIn>
          )}
        </div>
      </section>

      {/* ================================================================ */}
      {/* GROUPED FAQ SECTIONS (filtered in real time)                     */}
      {/* ================================================================ */}
      {filteredGroups.length > 0 ? (
        filteredGroups.map((g) => (
          <div key={g.id} id={g.id} className={g.bg}>
            <FAQSection
              eyebrow={
                isSearching
                  ? `${g.eyebrow} · ${g.items.length} match${
                      g.items.length === 1 ? "" : "es"
                    }`
                  : g.eyebrow
              }
              title={g.title}
              subtitle={g.subtitle}
              items={g.items}
              highlight={isSearching ? query.trim() : undefined}
            />
          </div>
        ))
      ) : (
        <section className="bg-white py-20 md:py-28">
          <div className="max-w-xl mx-auto px-4 sm:px-6 text-center">
            <AnimateIn>
              <div className="w-16 h-16 rounded-2xl bg-[#0e6305]/10 text-[#0e6305] flex items-center justify-center mx-auto mb-5">
                <SearchX className="w-8 h-8" />
              </div>
              <h3 className="text-2xl font-black text-slate-900">
                No matching questions
              </h3>
              <p className="mt-3 text-slate-600">
                We couldn’t find an FAQ for{" "}
                <span className="font-semibold text-slate-800">
                  “{query.trim()}”
                </span>
                . Try a different keyword, or reach out and we’ll answer
                personally.
              </p>
              <div className="mt-6 flex flex-wrap gap-3 justify-center">
                <button
                  type="button"
                  onClick={() => setQuery("")}
                  className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-slate-900 hover:bg-slate-800 text-white font-bold text-sm uppercase tracking-wider transition"
                >
                  <X className="w-4 h-4" />
                  Clear search
                </button>
                <Link
                  to="/contact"
                  className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-[#0e6305] hover:bg-[#0a4a04] text-white font-bold text-sm uppercase tracking-wider transition"
                >
                  <Phone className="w-4 h-4" />
                  Contact Support
                </Link>
              </div>
            </AnimateIn>
          </div>
        </section>
      )}

      {/* ================================================================ */}
      {/* BOTTOM CTA                                                       */}
      {/* ================================================================ */}
      <section className="relative bg-black text-white py-20 md:py-24 overflow-hidden">
        <div
          aria-hidden="true"
          className="absolute inset-0 bg-gradient-to-br from-[#031a05] via-black to-[#05130a]"
        />
        <div
          aria-hidden="true"
          className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[400px] rounded-full bg-[#0e6305]/20 blur-[160px]"
        />
        <div className="relative max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <AnimateIn>
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#d4af37]/40 bg-[#d4af37]/5 text-[#f0d674] text-xs font-bold uppercase tracking-widest mb-6">
              <Zap className="w-3.5 h-3.5" />
              Still have questions?
            </div>
            <h2 className="text-3xl md:text-4xl font-black leading-tight">
              Our team is{" "}
              <span className="bg-gradient-to-r from-[#22c55e] to-[#d4af37] bg-clip-text text-transparent">
                one message away
              </span>
            </h2>
            <p className="mt-4 text-slate-300/90 max-w-2xl mx-auto">
              Technical, billing, or strategic — reach out and a real human will
              get back to you within minutes.
            </p>
            <div className="mt-8 flex flex-wrap gap-3 justify-center">
              <Link
                to="/contact"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-[#0e6305] hover:bg-[#0a4a04] text-white font-bold text-sm uppercase tracking-wider shadow-lg shadow-[#0e6305]/30 transition-all hover:-translate-y-0.5"
              >
                <Phone className="w-4 h-4" />
                Contact Support
                <ArrowRight className="w-4 h-4" />
              </Link>
              <Link
                to="/knowledge-base"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-[#d4af37] hover:bg-[#b8962e] text-black font-bold text-sm uppercase tracking-wider shadow-lg shadow-[#d4af37]/20 transition-all hover:-translate-y-0.5"
              >
                <BookOpen className="w-4 h-4" />
                Knowledge Base
              </Link>
              <Link
                to="/bizmail360"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full !bg-transparent !hover:bg-transparent border border-white/20 hover:border-[#d4af37]/60 text-white hover:text-[#d4af37] font-bold text-sm uppercase tracking-wider transition-all hover:-translate-y-0.5"
              >
                <Mail className="w-4 h-4" />
                Email Us
              </Link>
              <Link
                to="/services"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full !bg-transparent !hover:bg-transparent border border-white/20 hover:border-[#d4af37]/60 text-white hover:text-[#d4af37] font-bold text-sm uppercase tracking-wider transition-all hover:-translate-y-0.5"
              >
                <ShieldCheck className="w-4 h-4" />
                View Services
              </Link>
            </div>
          </AnimateIn>
        </div>
      </section>
    </SiteLayout>
  );
}