"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { Plus, Minus, MessageSquareText, ChevronRight, Search, Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";

interface FAQ {
  question: string;
  answer: string;
  category: string;
}

const faqData: FAQ[] = [
  {
    question: "How long is the server setup process after payment?",
    answer: "Instant! Our system automatically detects your payment. Your server will be active and ready within 60 seconds after the invoice is paid (Dedicated Servers require 1–24 hours for manual setup).",
    category: "General",
  },
  {
    question: "Can I upgrade my plan mid-cycle?",
    answer: "Absolutely. You can upgrade RAM/CPU at any time through the Client Area. The system calculates the prorated difference, you only pay for the difference and no data is lost during the transition.",
    category: "Billing",
  },
  {
    question: "Which server location is best for me?",
    answer: "Use the Ping Tester on our homepage. Generally: Jakarta for majority Indonesian players, Singapore for Southeast Asia, and the US for global communities.",
    category: "Technical",
  },
  {
    question: "Is DDoS protection included?",
    answer: "Yes, all plans include standard Layer 4 & 7 DDoS protection. Flux and Atlas plans add specialized game mitigation (Game Firewall) that aggressively filters targeted attacks.",
    category: "Security",
  },
  {
    question: "What payment methods are accepted?",
    answer: "We accept QRIS (GoPay, OVO, Dana), Bank Virtual Accounts (BCA, Mandiri, BRI, BNI), and retail outlets like Alfamart and Indomaret.",
    category: "Billing",
  },
  {
    question: "Can I install mods or plugins myself?",
    answer: "Absolutely. You have full File Manager and SFTP access. Upload any .jar, modpack, or plugins. As long as it doesn't violate our ToS (no crypto mining or malicious scripts).",
    category: "Technical",
  },
];

const categoryStyle: Record<string, string> = {
  "General":  "text-content-dim  bg-zinc-800/60   border-border-hover/50",
  "Billing":  "text-emerald-400 bg-emerald-500/8 border-emerald-500/20",
  "Technical":"text-sky-400    bg-sky-500/8     border-sky-500/20",
  "Security": "text-violet-400 bg-violet-500/8  border-violet-500/20",
};

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",
};

function FAQItem({
  faq,
  isOpen,
  onClick,
  index,
}: {
  faq: FAQ;
  isOpen: boolean;
  onClick: () => void;
  index: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-40px" }}
      transition={{ delay: index * 0.05, duration: 0.4, ease: "easeOut" }}
      className={cn(
        "rounded-2xl overflow-hidden border transition-colors duration-300",
        isOpen
          ? "border-accent-hover/25 bg-accent-hover/4"
          : "border-border/80 bg-surface hover:border-border-hover hover:bg-elevated"
      )}
    >
      <button
        onClick={onClick}
        className="w-full flex items-center justify-between p-6 text-left cursor-pointer group gap-4"
      >
        <div className={cn("flex flex-col flex-1 min-w-0", isOpen ? "gap-2" : "gap-0")}>
          <span className={cn(
            "inline-flex items-center gap-1.5 text-[9px] font-bold uppercase tracking-widest w-fit px-2.5 py-1 rounded-full border transition-all duration-300",
            categoryStyle[faq.category] ?? "text-content-dim bg-zinc-800/60 border-border-hover/50",
            isOpen ? "opacity-100" : "opacity-0 h-0 overflow-hidden py-0 mb-0"
          )}>
            <span className="w-1 h-1 rounded-full bg-current" />
            {faq.category}
          </span>

          <span className={cn(
            "text-base font-medium transition-colors duration-300 leading-snug",
            isOpen ? "text-white" : "text-zinc-300 group-hover:text-white"
          )}>
            {faq.question}
          </span>
        </div>

        <div className={cn(
          "shrink-0 w-8 h-8 rounded-xl border flex items-center justify-center transition-all duration-300",
          isOpen
            ? "bg-accent-hover/10 border-accent-hover/25 text-accent-text"
            : "bg-zinc-900 border-border text-content-muted group-hover:text-zinc-300 group-hover:border-border-hover"
        )}>
          {isOpen ? <Minus className="w-3.5 h-3.5" /> : <Plus className="w-3.5 h-3.5" />}
        </div>
      </button>

      <AnimatePresence initial={false}>
        {isOpen && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.35, ease: [0.04, 0.62, 0.23, 0.98] }}
          >
            <div className="px-6 pb-6 pt-0">
              <div className="h-px bg-zinc-800/80 mb-5" />
              <p className="text-content-dim leading-relaxed text-sm">{faq.answer}</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

export default function FaqSection() {
  const [searchQuery, setSearchQuery] = useState("");
  const [openIndex, setOpenIndex]     = useState<number | null>(0);

  const filteredFAQs = faqData.filter(
    (item) =>
      item.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.answer.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <section
      className="relative w-full py-24 md:py-32 px-6 lg:px-12 overflow-hidden font-sans border-t border-border/80"
    >
      <div className="absolute inset-0 opacity-[0.03] pointer-events-none z-0" style={noiseStyle} />

      <div className="max-w-3xl mx-auto relative z-10">

        <motion.div
          initial={{ opacity: 0, y: 14 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
          className="mb-14 md:mb-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">Help Center</p>
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
          </div>
          <h2 className="text-4xl md:text-5xl font-semibold tracking-tight text-white leading-[1.1] mb-8">
            Frequently asked <br />
            <span className="text-accent-text">questions.</span>
          </h2>

          <div className="relative group w-full">
            <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
              <Search className="w-4 h-4 text-content-subtle group-focus-within:text-accent-text transition-colors duration-200" />
            </div>
            <input
              type="text"
              placeholder="Search questions…"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full rounded-xl py-3.5 pl-11 pr-5 text-sm text-zinc-200 placeholder-zinc-600 bg-surface border border-border/80 outline-none transition-all duration-200 focus:border-accent-hover/40 focus:ring-2 focus:ring-accent-hover/40"
            />
          </div>
        </motion.div>

        <div className="space-y-2.5">
          <AnimatePresence>
            {filteredFAQs.length > 0 ? (
              filteredFAQs.map((faq, index) => (
                <FAQItem
                  key={faq.question}
                  faq={faq}
                  isOpen={openIndex === index}
                  onClick={() => setOpenIndex(openIndex === index ? null : index)}
                  index={index}
                />
              ))
            ) : (
              <motion.div
                initial={{ opacity: 0, scale: 0.97 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0 }}
                className="text-center py-16 px-6 rounded-2xl border border-border/80 bg-surface"
              >
                <p className="text-content-muted text-sm mb-3">No results for "{searchQuery}"</p>
                <button
                  onClick={() => setSearchQuery("")}
                  className="text-accent-text hover:text-accent-hover font-medium text-xs transition-colors"
                >
                  Clear search
                </button>
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        <motion.div
          initial={{ opacity: 0, y: 16 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5, delay: 0.2 }}
          className="mt-12 flex flex-col items-center text-center p-8 rounded-2xl border border-border/80 bg-surface"
        >
          <p className="text-content-dim text-[1rem] mb-6 leading-relaxed">
            Still have questions? <br />
            <span className="text-white font-bold text-xl">Our team is here to help.</span>
          </p>
          <a
            href="/support"
            className="inline-flex items-center gap-2.5 px-6 py-3 rounded-xl border border-border bg-zinc-900/60 text-zinc-300 font-semibold text-sm transition-all duration-200 group hover:border-accent-hover/30 hover:bg-accent-hover/6 hover:text-white"
          >
            <MessageSquareText className="w-4 h-4 text-accent-text group-hover:scale-110 transition-transform duration-200" />
            Open Support
            <ChevronRight className="w-3.5 h-3.5 text-content-subtle group-hover:translate-x-0.5 group-hover:text-accent-text transition-all duration-200" />
          </a>
        </motion.div>

      </div>
    </section>
  );
}
