"use client";
import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { ChevronRight, Search, Download, HelpCircle, FileText, Play, Clock, Calendar, ChevronDown, Check } from "lucide-react";
import { SpotlightCard } from "../SpotlightCard";

export interface FAQItem {
  category: string;
  question: string;
  answer: string;
}

export interface DownloadItem {
  title: string;
  category: string;
  size: string;
}

export interface WebinarItem {
  title: string;
  duration: string;
  speaker: string;
  date: string;
}

interface SupportLayoutProps {
  title: string;
  tagline: string;
  breadcrumb: string;
  intro: string;
  faqs?: FAQItem[];
  downloads?: DownloadItem[];
  webinars?: WebinarItem[];
}

export default function SupportLayout({
  title,
  tagline,
  breadcrumb,
  intro,
  faqs = [],
  downloads = [],
  webinars = [],
}: SupportLayoutProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeFaq, setActiveFaq] = useState<number | null>(null);
  const [activeCategory, setActiveCategory] = useState("all");
  const [downloadingIdx, setDownloadingIdx] = useState<number | null>(null);

  // Extract unique FAQ categories
  const faqCategories = ["all", ...Array.from(new Set(faqs.map((f) => f.category.toLowerCase())))];

  // Filter FAQs based on active category and search query
  const filteredFaqs = faqs.filter((faq) => {
    const matchesCategory = activeCategory === "all" || faq.category.toLowerCase() === activeCategory;
    const matchesSearch =
      faq.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
      faq.answer.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCategory && matchesSearch;
  });

  const handleDownload = (idx: number) => {
    setDownloadingIdx(idx);
    setTimeout(() => {
      setDownloadingIdx(null);
    }, 1500);
  };

  return (
    <div className="relative min-h-screen overflow-hidden bg-orbit-bg-deep orbit-grid-mesh">
      {/* Background Glow */}
      <div className="absolute top-[-10%] left-[-10%] h-[500px] w-[500px] rounded-full bg-orbit-blue/10 blur-[120px]" />
      <div className="absolute bottom-[10%] right-[-10%] h-[600px] w-[600px] rounded-full bg-orbit-purple/8 blur-[130px]" />

      <main className="mx-auto max-w-7xl px-4 py-8 md:px-8">
        
        {/* Breadcrumb */}
        <div className="mb-6 flex items-center gap-2 text-xs font-mono text-slate-500">
          <Link href="/" className="hover:text-orbit-cyan">Home</Link>
          <ChevronRight className="h-3 w-3" />
          <Link href="/support" className="hover:text-orbit-cyan">Support</Link>
          <ChevronRight className="h-3 w-3" />
          <span className="text-slate-600 dark:text-slate-300">{breadcrumb}</span>
        </div>

        {/* Hero Section */}
        <section className="mb-12 max-w-3xl">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="space-y-4"
          >
            <div className="inline-flex rounded-full border border-orbit-cyan/20 bg-orbit-cyan/5 px-3 py-1 font-mono text-[10px] font-bold uppercase tracking-widest text-orbit-cyan">
              Orbit Help Desk
            </div>
            <h1 className="text-4xl font-extrabold tracking-tight text-slate-900 dark:text-white sm:text-5xl">
              {title} <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">{tagline}</span>
            </h1>
            <p className="text-sm leading-relaxed text-slate-600 dark:text-slate-400 sm:text-base">
              {intro}
            </p>
          </motion.div>
        </section>

        {/* Dynamic FAQ Accordions with Search */}
        {faqs.length > 0 && (
          <section className="mb-16 grid gap-8 lg:grid-cols-12">
            
            {/* Left Column: Sidebar Filters */}
            <div className="lg:col-span-4 space-y-4">
              <div className="rounded-3xl border border-orbit-border bg-orbit-bg-primary/80 p-5 shadow-xl backdrop-blur-sm">
                <div className="relative mb-6">
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Search FAQ repository..."
                    className="w-full rounded-2xl border border-orbit-border bg-orbit-bg-deep py-3 pl-11 pr-4 text-xs font-mono text-slate-800 dark:text-slate-200 outline-none focus:border-orbit-cyan focus:ring-1 focus:ring-orbit-cyan"
                  />
                  <Search className="absolute left-4 top-3.5 h-4.5 w-4.5 text-slate-500" />
                </div>

                <div className="space-y-1.5">
                  <span className="block font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest px-3 mb-2">
                    Topic Filter
                  </span>
                  {faqCategories.map((cat) => (
                    <button
                      key={cat}
                      onClick={() => setActiveCategory(cat)}
                      className={`flex w-full items-center justify-between rounded-xl px-3 py-2 text-xs font-mono font-bold capitalize transition-colors ${
                        activeCategory === cat
                          ? "bg-orbit-cyan/15 border border-orbit-cyan/20 text-orbit-cyan"
                          : "border border-transparent text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-900/50 hover:text-slate-900 dark:hover:text-slate-800 dark:text-slate-200"
                      }`}
                    >
                      <span>{cat}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* Right Column: FAQ Accordion List */}
            <div className="lg:col-span-8 space-y-4">
              <AnimatePresence mode="popLayout">
                {filteredFaqs.map((faq, idx) => {
                  const isOpen = activeFaq === idx;
                  return (
                    <motion.div
                      layout
                      key={faq.question}
                      initial={{ opacity: 0, y: 15 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -15 }}
                      transition={{ duration: 0.25 }}
                      className="overflow-hidden rounded-2xl border border-orbit-border bg-orbit-bg-secondary/40 backdrop-blur-sm"
                    >
                      <button
                        onClick={() => setActiveFaq(isOpen ? null : idx)}
                        className="flex w-full items-center justify-between p-5 text-left text-xs font-bold text-slate-900 dark:text-white hover:text-orbit-cyan transition-colors"
                      >
                        <span className="flex items-center gap-3">
                          <HelpCircle className="h-4.5 w-4.5 text-orbit-cyan shrink-0" />
                          {faq.question}
                        </span>
                        <ChevronDown className={`h-4 w-4 shrink-0 transition-transform duration-300 ${isOpen ? "rotate-180 text-orbit-cyan" : "text-slate-500"}`} />
                      </button>

                      <AnimatePresence initial={false}>
                        {isOpen && (
                          <motion.div
                            initial={{ height: 0 }}
                            animate={{ height: "auto" }}
                            exit={{ height: 0 }}
                            transition={{ duration: 0.3, ease: "easeInOut" }}
                          >
                            <div className="border-t border-orbit-border bg-orbit-bg-deep/40 p-5 text-xs leading-relaxed text-slate-600 dark:text-slate-400">
                              {faq.answer}
                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </motion.div>
                  );
                })}
              </AnimatePresence>

              {filteredFaqs.length === 0 && (
                <div className="text-center rounded-2xl border border-dashed border-orbit-border bg-orbit-bg-secondary/20 p-12">
                  <span className="block font-mono text-xs text-slate-500 font-bold uppercase">No matching FAQs discovered</span>
                </div>
              )}
            </div>
          </section>
        )}

        {/* Resources / Downloads grid */}
        {downloads.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 border-b border-orbit-border pb-3">
              <h2 className="text-xl font-bold tracking-tight text-slate-900 dark:text-white sm:text-2xl">
                Technical <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Downloads</span>
              </h2>
              <p className="text-xs text-slate-500 mt-1">Brochures, protocol manuals, and SDK specification drafts.</p>
            </div>

            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {downloads.map((dl, idx) => (
                <SpotlightCard key={dl.title} className="rounded-3xl p-5 flex flex-col justify-between">
                  <div className="flex gap-4">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-orbit-cyan/10 border border-orbit-cyan/20">
                      <FileText className="h-4.5 w-4.5 text-orbit-cyan" />
                    </div>
                    <div className="space-y-1">
                      <h3 className="text-xs font-bold text-slate-900 dark:text-white leading-snug">{dl.title}</h3>
                      <div className="flex gap-2 font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest">
                        <span>{dl.category}</span>
                        <span>·</span>
                        <span>{dl.size}</span>
                      </div>
                    </div>
                  </div>

                  <div className="mt-6 border-t border-orbit-border pt-4">
                    <button
                      onClick={() => handleDownload(idx)}
                      disabled={downloadingIdx !== null}
                      className={`flex w-full items-center justify-center gap-2 rounded-xl py-2 text-xs font-mono font-bold transition-all ${
                        downloadingIdx === idx
                          ? "bg-orbit-green/20 border border-orbit-green/30 text-orbit-green"
                          : "border border-orbit-border bg-orbit-bg-deep/50 text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white"
                      }`}
                    >
                      {downloadingIdx === idx ? (
                        <>
                          <Check className="h-3.5 w-3.5 animate-pulse" />
                          <span>COMPLETED</span>
                        </>
                      ) : (
                        <>
                          <Download className="h-3.5 w-3.5" />
                          <span>GET RESOURCE</span>
                        </>
                      )}
                    </button>
                  </div>
                </SpotlightCard>
              ))}
            </div>
          </section>
        )}

        {/* Webinars / Learning media list */}
        {webinars.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 border-b border-orbit-border pb-3">
              <h2 className="text-xl font-bold tracking-tight text-slate-900 dark:text-white sm:text-2xl">
                E-Learning & <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Webinars</span>
              </h2>
              <p className="text-xs text-slate-500 mt-1">Live recorded sessions on industrial optimization methodologies.</p>
            </div>

            <div className="grid gap-6 md:grid-cols-2">
              {webinars.map((web) => (
                <div
                  key={web.title}
                  className="group relative overflow-hidden rounded-3xl border border-orbit-border bg-orbit-bg-secondary/40 p-6 backdrop-blur-sm shadow-xl flex flex-col justify-between"
                >
                  <div className="relative h-44 w-full rounded-2xl bg-orbit-bg-deep border border-slate-200 dark:border-slate-800 overflow-hidden flex items-center justify-center mb-4">
                    {/* Simulated video poster gradient */}
                    <div className="absolute inset-0 bg-gradient-to-tr from-orbit-cyan/5 via-orbit-purple/5 to-slate-900/50" />
                    <button className="relative flex h-12 w-12 items-center justify-center rounded-full bg-orbit-cyan shadow-[0_0_15px_rgba(0,212,255,0.4)] group-hover:scale-110 active:scale-95 transition-transform duration-300">
                      <Play className="h-5 w-5 fill-white text-slate-900 dark:text-white ml-0.5" />
                    </button>
                  </div>

                  <div>
                    <h3 className="text-sm font-bold text-slate-900 dark:text-white group-hover:text-orbit-cyan transition-colors font-sans">
                      {web.title}
                    </h3>
                    <div className="mt-4 flex flex-wrap gap-4 font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest">
                      <span className="flex items-center gap-1.5">
                        <Clock className="h-3 w-3" />
                        {web.duration}
                      </span>
                      <span className="flex items-center gap-1.5">
                        <Calendar className="h-3 w-3" />
                        {web.date}
                      </span>
                      <span>Speaker: {web.speaker}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}

      </main>
    </div>
  );
}
