"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "motion/react";
import {
  Search, X, HelpCircle, CreditCard, ScrollText,
  ChevronRight, FileText, Rocket, Server, ArrowRight, Phone
} from "lucide-react";
import { cn } from "@/lib/utils";
import { sidebar } from "@/lib/docs-sidebar";

const noiseStyle = {
  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",
};

const catIconMap: Record<string, React.ElementType> = {
  Rocket,
  Server,
  CreditCard,
};

const allDocItems = sidebar.flatMap((cat) =>
  cat.articles.map((a) => ({
    type: "doc" as const,
    title: a.title,
    category: cat.category,
    href: `/support/docs/${cat.slug}/${a.slug}`,
    keywords: `${cat.category} ${a.title} ${a.slug}`.toLowerCase(),
  }))
);

const quickLinks = [
  {
    title: "Billing & Payment",
    icon: CreditCard,
    desc: "Invoices, credits, and payment methods.",
    href: "/support/billing",
  },
  {
    title: "Legal & Policies",
    icon: ScrollText,
    desc: "Terms of service, privacy, and SLA.",
    href: "/support/legal",
  },
  {
    title: "Contact Us",
    icon: Phone,
    desc: "Get in touch with our support team.",
    href: "/support/contact",
  },
];

const searchItems = [
  ...allDocItems,
  { type: "link" as const, title: "QnA Center",        category: "Support", href: "/support/qna",     keywords: "qna questions answers help" },
  { type: "link" as const, title: "Billing & Payment",  category: "Support", href: "/support/billing", keywords: "billing payment invoice credit" },
  { type: "link" as const, title: "Legal & Policies",   category: "Support", href: "/support/legal",   keywords: "legal terms privacy sla policy tos" },
];

export default function SupportPage() {
  const router = useRouter();
  const [query, setQuery]   = useState("");
  const [focused, setFocused] = useState(false);

  const results = query.trim().length > 1
    ? searchItems.filter((item) => item.keywords.includes(query.toLowerCase().trim()))
    : [];

  const showDropdown = focused && query.trim().length > 1;

  return (
    <main className="flex flex-col items-center w-full min-h-screen bg-base text-white font-sans selection:bg-accent-hover/30 overflow-x-hidden">
      <div className="fixed inset-0 opacity-[0.025] pointer-events-none z-0" style={noiseStyle} />
      <div
        className="fixed top-0 left-1/2 -translate-x-1/2 w-[900px] h-[600px] rounded-full blur-[180px] opacity-[0.07] pointer-events-none z-0"
        style={{ background: "radial-gradient(ellipse, var(--accent-glow), transparent)" }}
      />

      <div className="relative z-10 w-full max-w-5xl px-6 lg:px-12">

        <section className="pt-36 pb-16 flex flex-col items-center text-center">
          <div className="flex items-center justify-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">Support Center</p>
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
          </div>

          <h1 className="text-5xl md:text-6xl font-semibold tracking-tight text-white leading-[1.05] mb-5">
            How can we <span className="text-accent-text">help you?</span>
          </h1>
          <p className="text-content-dim text-[1rem] md:text-lg max-w-md leading-relaxed mb-10">
            Browse guides, check policies, or search for exactly what you need.
          </p>

          <div className="relative w-full max-w-xl">
            <Search className="absolute left-4 inset-y-0 my-auto w-4 h-4 text-content-subtle pointer-events-none" />
            <input
              type="text"
              placeholder="Search guides, billing, legal…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onFocus={() => setFocused(true)}
              onBlur={() => setTimeout(() => setFocused(false), 150)}
              className="w-full bg-surface border border-border/80 rounded-xl py-3.5 pl-11 pr-10 text-white placeholder-zinc-600 focus:outline-none focus:border-accent-hover/40 focus:ring-2 focus:ring-accent-hover/8 transition-all text-sm"
            />
            {query && (
              <button onClick={() => setQuery("")} className="absolute inset-y-0 right-4 flex items-center">
                <X className="w-4 h-4 text-content-muted hover:text-white transition-colors" />
              </button>
            )}

            <AnimatePresence>
              {showDropdown && (
                <motion.div
                  initial={{ opacity: 0, y: -6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -6 }}
                  transition={{ duration: 0.15 }}
                  className="absolute top-full mt-2 left-0 right-0 bg-surface border border-border/80 rounded-xl shadow-2xl overflow-hidden z-50"
                >
                  {results.length > 0 ? (
                    <div className="py-1.5">
                      {results.slice(0, 8).map((item, i) => (
                        <button
                          key={i}
                          onMouseDown={() => router.push(item.href)}
                          className="w-full flex items-center justify-between gap-3 px-4 py-3 hover:bg-zinc-800/50 transition-colors text-left group"
                        >
                          <div className="flex items-center gap-3 min-w-0">
                            <FileText className="w-3.5 h-3.5 text-content-subtle shrink-0" />
                            <div className="min-w-0">
                              <p className="text-sm text-zinc-200 font-medium truncate">{item.title}</p>
                              <p className="text-xs text-content-subtle truncate">{item.category}</p>
                            </div>
                          </div>
                          <ChevronRight className="w-3.5 h-3.5 text-content-faint group-hover:text-accent-text transition-colors shrink-0" />
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="py-8 text-center">
                      <p className="text-sm text-content-subtle">No results for &quot;{query}&quot;</p>
                    </div>
                  )}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </section>

        <section className="pb-16">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {quickLinks.map((card) => {
              const Icon = card.icon;
              return (
                <Link
                  key={card.href}
                  href={card.href}
                  className="group flex items-start gap-4 p-5 rounded-2xl bg-surface border border-border/80 hover:border-border-hover hover:bg-elevated transition-all duration-300"
                >
                  <div className="w-9 h-9 rounded-xl bg-zinc-900 border border-border flex items-center justify-center shrink-0 group-hover:border-border-hover transition-colors">
                    <Icon className="w-4 h-4 text-accent-text" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-white text-sm mb-1 group-hover:text-accent-text/80 transition-colors">{card.title}</h3>
                    <p className="text-xs text-content-muted leading-relaxed">{card.desc}</p>
                  </div>
                  <ArrowRight className="w-4 h-4 text-content-faint group-hover:text-accent-text transition-colors shrink-0 mt-0.5" />
                </Link>
              );
            })}
          </div>
        </section>

        <section className="pb-28">
          <div className="flex items-center gap-3 mb-10">
            <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">Documentation</p>
          </div>

          <div className="space-y-10">
            {sidebar.map((cat, catIdx) => {
              const Icon = catIconMap[cat.icon] ?? Server;
              return (
                <motion.div
                  key={cat.slug}
                  initial={{ opacity: 0, y: 16 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.5, delay: catIdx * 0.08 }}
                >
                  <div className="flex items-center gap-3 mb-4">
                    <div className="w-8 h-8 rounded-lg bg-zinc-900 border border-border flex items-center justify-center shrink-0">
                      <Icon className="w-4 h-4 text-accent-text" />
                    </div>
                    <h2 className="font-semibold text-white text-sm tracking-tight">{cat.category}</h2>
                    <span className="text-[10px] font-bold text-content-faint uppercase tracking-widest">
                      {cat.articles.length} articles
                    </span>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 pl-0">
                    {cat.articles.map((article) => (
                      <Link
                        key={article.slug}
                        href={`/support/docs/${cat.slug}/${article.slug}`}
                        className="group flex items-center justify-between gap-3 px-4 py-3.5 rounded-xl bg-surface border border-border/80 hover:border-accent-hover/30 hover:bg-elevated transition-all duration-200"
                      >
                        <div className="flex items-center gap-3 min-w-0">
                          <FileText className="w-3.5 h-3.5 text-content-faint group-hover:text-accent-text transition-colors shrink-0" />
                          <span className="text-sm text-content-dim group-hover:text-zinc-200 transition-colors truncate font-medium">
                            {article.title}
                          </span>
                        </div>
                        <ChevronRight className="w-3.5 h-3.5 text-content-faint group-hover:text-accent-text transition-colors shrink-0" />
                      </Link>
                    ))}
                  </div>
                </motion.div>
              );
            })}
          </div>
        </section>

      </div>
    </main>
  );
}
