"use client";

import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { MagnifyingGlass, CaretDown, Question } from "@phosphor-icons/react";
import { AnimatedSection, AnimatedItem } from "@/components/ui/AnimatedSection";
import EyebrowBadge from "@/components/ui/EyebrowBadge";

type FAQItem = {
  id: string;
  category: "cost" | "technical" | "warranty";
  question: string;
  answer: string;
};

const FAQS: FAQItem[] = [
  {
    id: "f1",
    category: "cost",
    question: "How much government subsidy (PM Surya Ghar) do I qualify for?",
    answer: "Under PM Surya Ghar Muft Bijli Yojana, residential rooftop systems receive ₹30,000 per kW up to 2 kW (₹60,000) plus ₹18,000 for the 3rd kW, capping at ₹78,000 total. CloudHelio handles all portal filings and DISCOM approvals directly for you.",
  },
  {
    id: "f2",
    category: "technical",
    question: "What happens on rainy or overcast monsoon days?",
    answer: "N-type TOPCon bifacial panels capture diffuse ambient radiation even on cloudy days, generating roughly 25-40% of peak output. Surplus credits stored in the grid during summer via Net Metering offset monsoon generation drops.",
  },
  {
    id: "f3",
    category: "warranty",
    question: "How long is the design lifespan of the solar system?",
    answer: "The solar panels are engineered with a design life of 25+ years, utilizing weather-tested materials to ensure minimal output degradation over decades. Inverters and electrical accessories are designed for a 10 to 12-year service life before requiring standard component servicing.",
  },
  {
    id: "f4",
    category: "technical",
    question: "Does the system keep running during a grid blackout?",
    answer: "Standard grid-tied systems shut off automatically during outages to prevent line worker electrocution. If you require uninterrupted backup, we add an intelligent hybrid battery storage system that seamlessly switches in under 10 milliseconds.",
  },
  {
    id: "f5",
    category: "cost",
    question: "What is the typical payback timeline for residential solar?",
    answer: "Most Indian residential solar systems achieve complete financial payback in 3.2 to 4.2 years depending on your local DISCOM tariff slab and subsidy eligibility — offering 20+ subsequent years of free electricity.",
  },
  {
    id: "f6",
    category: "warranty",
    question: "How often do solar panels require cleaning and maintenance?",
    answer: "Panels require basic dust cleaning every 2–4 weeks. CloudHelio includes 1 year of complimentary bi-monthly maintenance checkups and 24/7 cloud mobile app monitoring that flags any string drop immediately.",
  },
];

export default function FAQSection() {
  const [activeCategory, setActiveCategory] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [openId, setOpenId] = useState<string | null>("f1");

  const filteredFaqs = useMemo(() => {
    return FAQS.filter((f) => {
      const matchesCategory = activeCategory === "all" || f.category === activeCategory;
      const matchesSearch =
        f.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
        f.answer.toLowerCase().includes(searchQuery.toLowerCase());
      return matchesCategory && matchesSearch;
    });
  }, [activeCategory, searchQuery]);

  return (
    <section className="relative z-10 overflow-hidden bg-zinc-950 px-6 py-24 md:px-8 md:py-32">
      <AnimatedSection className="mx-auto max-w-[1000px]">
        <div className="mb-12 text-center">
          <AnimatedItem>
            <EyebrowBadge tone="dark" className="mb-4">
              Clear Answers
            </EyebrowBadge>
          </AnimatedItem>
          <AnimatedItem>
            <h2 className="text-3xl font-semibold tracking-tight text-white md:text-5xl">
              Frequently Asked Questions
            </h2>
          </AnimatedItem>
          <AnimatedItem>
            <p className="mt-4 text-sm text-zinc-400 md:text-base">
              Everything you need to know about rooftop solar installation, subsidies, and maintenance.
            </p>
          </AnimatedItem>
        </div>

        {/* Live Filter Controls */}
        <div className="mb-8 flex flex-col items-center justify-between gap-4 sm:flex-row">
          {/* Category Tabs */}
          <div className="flex flex-wrap gap-2">
            {[
              { id: "all", label: "All Questions" },
              { id: "cost", label: "Cost & Subsidy" },
              { id: "technical", label: "Technical & Grid" },
              { id: "warranty", label: "Lifespan & Maintenance" },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveCategory(tab.id)}
                className={`rounded-xl px-3.5 py-1.5 text-xs font-semibold transition-all duration-300 ${
                  activeCategory === tab.id
                    ? "bg-amber-500 text-zinc-950 font-bold shadow-[0_0_12px_rgba(245,158,11,0.4)]"
                    : "border border-white/10 bg-zinc-900/60 text-zinc-400 hover:text-white"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Search Bar */}
          <div className="relative w-full max-w-xs">
            <MagnifyingGlass size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-zinc-400" />
            <input
              type="text"
              placeholder="Search questions..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full rounded-2xl border border-white/10 bg-zinc-900/80 pl-10 pr-4 py-2 text-xs text-white placeholder-zinc-500 focus:border-amber-400 focus:outline-none"
            />
          </div>
        </div>

        {/* Accordions */}
        <div className="space-y-4">
          {filteredFaqs.length > 0 ? (
            filteredFaqs.map((faq) => {
              const isOpen = openId === faq.id;
              return (
                <AnimatedItem key={faq.id}>
                  <div
                    className={`overflow-hidden rounded-2xl border transition-all duration-300 ${
                      isOpen
                        ? "border-amber-400/40 bg-zinc-900/90 shadow-[0_0_20px_rgba(245,158,11,0.15)]"
                        : "border-white/10 bg-zinc-900/40 hover:border-white/20"
                    }`}
                  >
                    <button
                      onClick={() => setOpenId(isOpen ? null : faq.id)}
                      className="flex w-full items-center justify-between p-5 text-left"
                    >
                      <span className="flex items-center gap-3 font-semibold text-white text-sm md:text-base">
                        <Question size={18} className="text-amber-400 shrink-0" />
                        {faq.question}
                      </span>
                      <CaretDown
                        size={18}
                        className={`shrink-0 text-amber-400 transition-transform duration-300 ${
                          isOpen ? "rotate-180" : ""
                        }`}
                      />
                    </button>
                    <AnimatePresence>
                      {isOpen && (
                        <motion.div
                          initial={{ height: 0, opacity: 0 }}
                          animate={{ height: "auto", opacity: 1 }}
                          exit={{ height: 0, opacity: 0 }}
                          transition={{ duration: 0.25 }}
                        >
                          <div className="border-t border-white/10 px-5 py-4 text-xs leading-relaxed text-zinc-300 md:text-sm">
                            {faq.answer}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                </AnimatedItem>
              );
            })
          ) : (
            <div className="rounded-2xl border border-white/10 p-8 text-center text-zinc-500 text-xs">
              No matching questions found for "{searchQuery}". Try searching another keyword or topic.
            </div>
          )}
        </div>
      </AnimatedSection>
    </section>
  );
}
