"use client";

import { useId, useMemo, useState } from "react";
import { ChevronRightIcon, CloseIcon, PlusIcon, SearchIcon } from "@/components/ui/Icons";
import { FAQ_CATEGORIES, FAQS, type FaqItem } from "@/data/faqs";
import { cn } from "@/lib/cn";

export function FaqSection() {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeCategoryId, setActiveCategoryId] = useState("individual-membership");
  // Set default open item to the first item (matches design photo)
  const [openItems, setOpenItems] = useState<Record<string, boolean>>({ "ind-1": true });

  const searchInputId = useId();

  // Toggle single accordion item
  const toggleItem = (id: string) => {
    setOpenItems((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  // Reset open FAQs when changing category
  const handleCategoryChange = (categoryId: string) => {
    setActiveCategoryId(categoryId);
    setOpenItems({});
  };

  const isSearching = searchQuery.trim().length > 0;

  // Filter FAQs based on search keywords
  const filteredFaqs = useMemo(() => {
    if (!isSearching) {
      return FAQS.filter((faq) => faq.category === activeCategoryId);
    }

    const query = searchQuery.toLowerCase().trim();
    return FAQS.filter((faq) => {
      const matchQ = faq.question.toLowerCase().includes(query);
      const matchA = faq.answer.toLowerCase().includes(query);
      const categoryObj = FAQ_CATEGORIES.find((c) => c.id === faq.category);
      const matchCat = categoryObj?.label.toLowerCase().includes(query) ?? false;
      return matchQ || matchA || matchCat;
    });
  }, [isSearching, searchQuery, activeCategoryId]);

  const activeCategory = FAQ_CATEGORIES.find((c) => c.id === activeCategoryId);

  return (
    <div className="w-full">
      {/* Top Banner with Circular Gradient (#7ba4d0 to #2e5e99) extending full width */}
      <section
        aria-labelledby="faq-page-heading"
        className="relative right-1/2 left-1/2 -mr-[50vw] -ml-[50vw] w-screen overflow-hidden py-16 sm:py-16 lg:py-17 text-white"
        style={{
          background: "radial-gradient(circle at 0% 0%, #7ba4d0 0%, #2e5e99 100%)",
        }}
      >
        <div className="mx-auto w-full max-w-[1440px] px-[3vw] min-[800px]:max-[1301px]:px-[3.8vw] max-[769px]:px-[5vw] text-left">
          <div className="pl-0 sm:pl-10 lg:pl-14 xl:pl-16">
            <h1
              id="faq-page-heading"
              className="text-[2.2rem] sm:text-[3rem] lg:text-[3.5rem] font-normal tracking-[0.5px] text-white"
            >
              Frequently Asked Questions
            </h1>

            {/* Search Bar (Left-aligned with expanded width) */}
            <div className="relative mt-8 sm:mt-10 w-full max-w-[1080px]">
              <label htmlFor={searchInputId} className="sr-only">
                Type keywords to find answers
              </label>
              <div className="relative flex items-center">
                <input
                  id={searchInputId}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Type keywords to find answers"
                  className="w-full rounded-[4px] sm:rounded-[6px] border border-white/30 bg-[#e7f0fa] py-3.5 pr-14 pl-5 sm:pl-6 text-[0.95rem] sm:text-[1rem] font-light text-[#2e5e99] placeholder-[#2e5e99] transition-all duration-200 outline-none focus:border-white/60 focus:bg-[#e7f0fa] focus:ring-2 focus:ring-[#2e5e99]/25"
                />

                <div className="absolute right-4 flex items-center gap-2">
                  {isSearching && (
                    <button
                      type="button"
                      onClick={() => setSearchQuery("")}
                      aria-label="Clear search query"
                      className="flex size-7 items-center justify-center rounded-full text-[#2e5e99] transition-colors hover:bg-[#2e5e99]/10"
                    >
                      <CloseIcon className="size-4" />
                    </button>
                  )}
                  <span className="pointer-events-none text-[#2e5e99]">
                    <SearchIcon className="size-5" />
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Main Content Area */}
      <section className="bg-white py-12 sm:py-16">
        <div className="mx-auto w-full max-w-[1440px] px-[3vw] min-[800px]:max-[1301px]:px-[3.8vw] max-[769px]:px-[5vw]">


          {/* Layout: Two Column on Desktop, single full-width column when searching */}
          <div
            className={cn(
              "grid items-start gap-8",
              isSearching
                ? "grid-cols-1 w-full"
                : "grid-cols-1 lg:grid-cols-[320px_1fr] xl:grid-cols-[360px_1fr]",
            )}
          >
            {/* Left Column: Categories List (hidden while searching) */}
            {!isSearching && (
              <aside
                aria-label="FAQ Categories Navigation"
                className="flex flex-col gap-3"
              >
                <h2 className="sr-only">Categories</h2>
                {FAQ_CATEGORIES.map((category) => {
                  const isSelected = activeCategoryId === category.id;
                  return (
                    <button
                      key={category.id}
                      type="button"
                      onClick={() => handleCategoryChange(category.id)}
                      className={cn(
                        "group flex w-full items-center justify-between rounded-[6px] px-5 py-4 text-left text-[0.975rem] font-medium tracking-[0.2px] transition-all duration-200",
                        isSelected
                          ? "bg-[#2e5e99] text-white shadow-sm"
                          : "bg-[#c5d5e8] text-white hover:bg-[#b3c7de]",
                      )}
                      aria-current={isSelected ? "true" : undefined}
                    >
                      <span>{category.label}</span>
                      <ChevronRightIcon
                        className={cn(
                          "size-5 transition-transform duration-200",
                          isSelected
                            ? "text-white translate-x-0.5"
                            : "text-white/90 group-hover:translate-x-0.5",
                        )}
                      />
                    </button>
                  );
                })}
              </aside>
            )}

            {/* Right Column: Accordion Questions */}
            <main
              id="faq-content-list"
              aria-label={
                isSearching
                  ? `Search results for ${searchQuery}`
                  : `${activeCategory?.label || "FAQ"} Questions`
              }
              className="flex flex-col gap-4"
            >
              <h2 className="sr-only">
                {isSearching
                  ? `Search results for ${searchQuery}`
                  : activeCategory?.label}
              </h2>

              {filteredFaqs.length > 0 ? (
                filteredFaqs.map((faq: FaqItem) => {
                  const isOpen = !!openItems[faq.id];

                  return (
                    <article
                      key={faq.id}
                      className={cn(
                        "rounded-[6px] bg-white transition-all duration-200",
                        isOpen
                          ? "border-2 border-[#2e5e99] p-4 sm:p-4 shadow-sm"
                          : "border border-[#e2e8f0] p-4 shadow-sm hover:border-[#cbd5e1]",
                      )}
                    >

                      {/* Accordion Trigger Header */}
                      <button
                        type="button"
                        onClick={() => toggleItem(faq.id)}
                        className="flex w-full items-start justify-between gap-4 text-left"
                        aria-expanded={isOpen}
                        aria-controls={`faq-answer-${faq.id}`}
                        id={`faq-question-${faq.id}`}
                      >
                        <h3
                          className={cn(
                            "text-[15px] leading-snug transition-colors",
                            isOpen
                              ? "font-bold text-black"
                              : "font-semibold text-[#8492a6] hover:text-[#64748b]",
                          )}
                        >
                          {faq.question}
                        </h3>

                        <span className="mt-0.5 shrink-0">
                          {isOpen ? (
                            <CloseIcon
                              className="size-[18px] text-[#2e5e99] transition-transform hover:scale-110"
                              aria-hidden="true"
                            />
                          ) : (
                            <PlusIcon
                              className="size-[18px] text-[#8492a6] transition-colors hover:text-[#64748b]"
                              aria-hidden="true"
                            />
                          )}
                        </span>
                      </button>

                      {/* Accordion Answer Content */}
                      {isOpen && (
                        <div
                          id={`faq-answer-${faq.id}`}
                          role="region"
                          aria-labelledby={`faq-question-${faq.id}`}
                          className="mt-4 text-[14px] leading-[1.65] text-[#4b5563]"
                        >
                          <p dangerouslySetInnerHTML={{ __html: faq.answer }} />
                        </div>
                      )}
                    </article>
                  );
                })
              ) : (
                /* No Results Empty State */
                <div className="flex flex-col items-center justify-center rounded-[8px] border border-dashed border-slate-300 bg-slate-50/75 p-12 text-center">
                  <div className="flex size-14 items-center justify-center rounded-full bg-blue-100/70 text-[#2e5e99]">
                    <SearchIcon className="size-7" />
                  </div>
                  <h3 className="mt-4 text-lg font-bold text-slate-800">
                    No matching questions found
                  </h3>
                  <p className="mt-2 max-w-md text-sm text-slate-600">
                    We couldn&apos;t find any FAQs matching &ldquo;{searchQuery}&rdquo;.
                    Try searching with different keywords like &ldquo;membership&rdquo;,
                    &ldquo;travel&rdquo;, or &ldquo;family&rdquo;.
                  </p>
                  <button
                    type="button"
                    onClick={() => setSearchQuery("")}
                    className="mt-5 rounded-[4px] bg-[#2e5e99] px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-[#234979]"
                  >
                    Clear search & view all categories
                  </button>
                </div>
              )}
            </main>
          </div>
        </div>
      </section>
    </div>
  );
}
