"use client";

import { useState, useEffect } from "react";
import { ChevronDown, Loader2 } from "lucide-react";
import AnimatedSection from "@/components/AnimatedSection";
import Link from "next/link";
import PageHeader from "@/components/ui/PageHeader";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { getALlFaq } from "@/lib/api/apis";
import { FAQCategory, FAQSubcategory } from "@/lib/faqUtils";

interface ExpandedState {
  faqs: { [key: string]: boolean };
}

export default function FAQPage() {
  const lang = getStoredLanguage();
  const t = getTranslation(lang);
  const { language } = useLanguage();

  const [categories, setCategories] = useState<FAQCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState<number | null>(null);
  const [activeSubcategory, setActiveSubcategory] = useState<number | null>(null);
  const [expanded, setExpanded] = useState<ExpandedState>({
    faqs: {},
  });

  useEffect(() => {
    const loadFAQs = async () => {
      try {
        const response = await getALlFaq();

        if (response.status && response.data?.categories) {
          setCategories(response.data.categories);
          // Set first category and subcategory as active by default
          if (response.data.categories.length > 0) {
            setActiveCategory(response.data.categories[0].category_id);
            if (response.data.categories[0].subcategories?.length > 0) {
              setActiveSubcategory(response.data.categories[0].subcategories[0].subcategory_id);
            }
          }
        } else {
          console.error("Failed to load FAQs:", response.message);
        }
      } catch (error) {
        console.error("Error loading FAQs:", error);
      } finally {
        setLoading(false);
      }
    };

    loadFAQs();
  }, []);

  const toggleFAQ = (faqId: string) => {
    setExpanded((prev) => ({
      ...prev,
      faqs: {
        ...prev.faqs,
        [faqId]: !prev.faqs[faqId],
      },
    }));
  };

  const getCurrentCategory = () => {
    return categories.find((c) => c.category_id === activeCategory);
  };

  const getCurrentSubcategory = () => {
    const category = getCurrentCategory();
    return category?.subcategories?.find((s) => s.subcategory_id === activeSubcategory);
  };

  return (
    <div>
      <PageHeader title={t.faq.pageTitle} breadcrumb={t.faq.breadcrumb} />

      <section className="bg-white pt-10 md:pt-16 pb-16 md:pb-24 border-b border-gray-100">
        <div className="container mx-auto px-4">
          {/* Header Section */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-10 md:gap-16 mb-12 lg:mb-16">
            <AnimatedSection className="lg:col-span-1">
              <span className="inline-block px-4 py-1.5 bg-[#FFF4E4] text-[#FAA631] rounded-full text-xs md:text-sm font-semibold mb-4">
                {t.faq.badge}
              </span>

              <h2 className="text-3xl md:text-4xl font-bold text-gray-900 leading-tight mb-4">
                {t.faq.titleStart}{" "}
                <span className="text-[#FAA631]">{t.faq.titleHighlight}</span>
              </h2>

              <p className="text-base md:text-lg text-gray-600 mb-6">
                {t.faq.description}
              </p>

              <div className="text-gray-700 text-sm md:text-base">
                {t.faq.stillNeedHelp}
                <Link
                  href="/contact"
                  className="text-[#FAA631] font-semibold hover:underline ml-1"
                >
                  {t.faq.contactSupport}
                </Link>
              </div>
            </AnimatedSection>

            {/* Content Area */}
            <div className="lg:col-span-2">
              {loading ? (
                <div className="flex items-center justify-center py-20">
                  <Loader2 className="w-8 h-8 text-[#FAA631] animate-spin" />
                </div>
              ) : categories.length === 0 ? (
                <p className="text-gray-500 text-center py-12">{t.faq.noFaq}</p>
              ) : (
                <div className="space-y-6">
                  {/* Main Tabs - Categories */}
                  <div className="flex flex-wrap gap-2 border-b border-gray-200 pb-4">
                    {categories.map((category) => {
                      const categoryName =
                        language === "hindi"
                          ? category.category_name_hindi
                          : category.category_name;
                      const isActive = activeCategory === category.category_id;

                      return (
                        <button
                          key={category.category_id}
                          onClick={() => {
                            setActiveCategory(category.category_id);
                            // Set first subcategory of new category as active
                            if (category.subcategories?.length > 0) {
                              setActiveSubcategory(category.subcategories[0].subcategory_id);
                            }
                          }}
                          className={`
                            px-4 md:px-6 py-2.5 rounded-t-lg font-semibold text-sm md:text-base transition-all duration-300
                            ${
                              isActive
                                ? "bg-[#FAA631] text-white shadow-md"
                                : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                            }
                          `}
                        >
                          {categoryName}
                        </button>
                      );
                    })}
                  </div>

                  {/* Sub Tabs - Subcategories */}
                  {getCurrentCategory()?.subcategories &&
                    getCurrentCategory()!.subcategories!.length > 0 && (
                      <div className="flex flex-wrap gap-2 pl-2 border-l-4 border-[#FAA631]">
                        {getCurrentCategory()!.subcategories!.map((subcategory) => {
                          const subcategoryName =
                            language === "hindi"
                              ? subcategory.subcategory_name_hindi
                              : subcategory.subcategory_name;
                          const isActive = activeSubcategory === subcategory.subcategory_id;

                          return (
                            <button
                              key={subcategory.subcategory_id}
                              onClick={() => setActiveSubcategory(subcategory.subcategory_id)}
                              className={`
                                px-4 py-2 rounded-lg font-medium text-sm transition-all duration-300
                                ${
                                  isActive
                                    ? "bg-[#FAA631] text-white"
                                    : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                                }
                              `}
                            >
                              {subcategoryName}
                            </button>
                          );
                        })}
                      </div>
                    )}

                  {/* FAQs List */}
                  <div className="space-y-3 pt-6">
                    {getCurrentSubcategory()?.faqs &&
                      getCurrentSubcategory()!.faqs!.length > 0 ? (
                      getCurrentSubcategory()!.faqs!.map((faq) => {
                        const faqKey = `faq-${faq.id}`;
                        const isFaqExpanded = expanded.faqs[faqKey];
                        const question =
                          language === "hindi" ? faq.question_hindi : faq.question;
                        const answer =
                          language === "hindi" ? faq.answer_hindi : faq.answer;

                        return (
                          <div
                            key={faqKey}
                            className="rounded-xl shadow-sm hover:shadow-md transition-shadow overflow-hidden border border-gray-200"
                          >
                            {/* FAQ Question */}
                            <button
                              onClick={() => toggleFAQ(faqKey)}
                              className={`
                                w-full flex justify-between items-center text-left px-5 md:px-6 py-4
                                text-sm md:text-base font-semibold transition-all duration-300
                                ${
                                  isFaqExpanded
                                    ? "bg-[#FAA631] text-white"
                                    : "bg-white text-gray-900 hover:bg-[#FFF4E4]"
                                }
                              `}
                            >
                              <span className="flex-1">{question}</span>
                              <ChevronDown
                                className={`w-5 h-5 transition-transform duration-300 flex-shrink-0 ml-4
                                  ${isFaqExpanded ? "rotate-180" : ""}`}
                              />
                            </button>

                            {/* FAQ Answer */}
                            {isFaqExpanded && (
                              <div className="px-5 md:px-6 py-4 text-gray-700 text-sm md:text-base leading-relaxed bg-gray-50 border-t border-gray-200">
                                <div
                                  dangerouslySetInnerHTML={{
                                    __html: answer,
                                  }}
                                  className="prose prose-sm max-w-none prose-p:my-2"
                                />
                              </div>
                            )}
                          </div>
                        );
                      })
                    ) : (
                      <p className="text-gray-500 text-center py-8">
                        {t.faq.noFaqsAvailable}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
