"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { ArrowRight, MessageCircle } from "lucide-react";
import { getWhatsAppUrl } from "@/lib/contact";

export type FaqItem = {
  id: number;
  category: string;
  question: string;
  answer: string;
  displayOrder: number;
  isActive: boolean;
};

export type FaqCategoryEntry = {
  category: string;
  items: FaqItem[];
};

function getCategoryId(category: string) {
  return `faq-${category
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "")}`;
}

export function FaqContent({ categories }: { categories: FaqCategoryEntry[] }) {
  const [activeCategory, setActiveCategory] = useState(categories[0]?.category ?? "");

  useEffect(() => {
    const categoryIds = categories.map(({ category }) => getCategoryId(category));
    const sections = categoryIds
      .map((id) => document.getElementById(id))
      .filter((section): section is HTMLElement => Boolean(section));

    const hashCategory = categories.find(
      ({ category }) => `#${getCategoryId(category)}` === window.location.hash,
    )?.category;

    if (hashCategory) {
      setActiveCategory(hashCategory);
    }

    const observer = new IntersectionObserver(
      (entries) => {
        const visibleEntry = entries
          .filter((entry) => entry.isIntersecting)
          .sort((first, second) => first.boundingClientRect.top - second.boundingClientRect.top)[0];

        if (!visibleEntry) {
          return;
        }

        const category = categories.find(
          (item) => getCategoryId(item.category) === visibleEntry.target.id,
        )?.category;

        if (category) {
          setActiveCategory(category);
        }
      },
      {
        rootMargin: "-20% 0px -65% 0px",
        threshold: 0,
      },
    );

    sections.forEach((section) => observer.observe(section));
    return () => observer.disconnect();
  }, [categories]);

  return (
    <div className="grid gap-8 lg:grid-cols-[280px_minmax(0,1fr)] lg:items-start">
      <aside className="lg:sticky lg:top-24">
        <div className="rounded-md border border-border bg-white p-4 shadow-sm">
          <p className="text-xs font-black uppercase tracking-[0.16em] text-primary">
            Browse topics
          </p>
          <div className="mt-4 space-y-2">
            {categories.map(({ category, items }) => {
              const isActive = category === activeCategory;

              return (
                <a
                  key={category}
                  href={`#${getCategoryId(category)}`}
                  onClick={() => setActiveCategory(category)}
                  className={`relative flex items-center justify-between gap-3 overflow-hidden rounded-md border px-3 py-2.5 pl-4 text-sm font-black transition ${
                    isActive
                      ? "border-primary/25 bg-primary/5 text-primary"
                      : "border-transparent text-muted-foreground hover:border-primary/20 hover:bg-primary/5 hover:text-primary"
                  }`}
                >
                  <span
                    className={`absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary transition ${
                      isActive ? "opacity-100" : "opacity-0"
                    }`}
                  />
                  <span className="truncate">{category}</span>
                  <span
                    className={`rounded-full px-2 py-0.5 text-[11px] transition ${
                      isActive
                        ? "bg-primary text-primary-foreground"
                        : "bg-slate-100 text-slate-600"
                    }`}
                  >
                    {items.length}
                  </span>
                </a>
              );
            })}
          </div>
        </div>

        <div className="mt-4 rounded-md border border-border bg-foreground p-5 text-background shadow-sm">
          <MessageCircle className="h-5 w-5 text-primary" />
          <h2 className="mt-3 text-lg font-black">Still need help?</h2>
          <p className="mt-2 text-sm font-medium leading-6 text-background/70">
            Send your question on WhatsApp and our team will guide you.
          </p>
          <Link
            href={getWhatsAppUrl()}
            target="_blank"
            rel="noreferrer"
            className="mt-4 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2.5 text-sm font-black text-primary-foreground transition hover:bg-primary/90"
          >
            Ask on WhatsApp
            <ArrowRight className="h-4 w-4" />
          </Link>
        </div>
      </aside>

      <div className="space-y-6">
        {categories.map(({ category, items }) => (
          <section
            key={category}
            id={getCategoryId(category)}
            aria-labelledby={`${getCategoryId(category)}-title`}
            className="scroll-mt-28 rounded-md border border-border bg-white shadow-sm"
          >
            <div className="border-b border-border px-5 py-5 sm:px-6">
              <p className="text-xs font-black uppercase tracking-[0.16em] text-primary">
                FAQ category
              </p>
              <h2
                id={`${getCategoryId(category)}-title`}
                className="mt-1 text-2xl font-black tracking-tight text-foreground"
              >
                {category}
              </h2>
            </div>

            <div className="divide-y divide-border">
              {items.map((faq, index) => (
                <details
                  key={faq.id}
                  open={index === 0}
                  className="group px-5 py-4 transition open:bg-slate-50 sm:px-6"
                >
                  <summary className="flex cursor-pointer list-none items-start justify-between gap-4 text-base font-black leading-6 text-foreground">
                    <span>{faq.question}</span>
                    <span className="mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-md border border-border bg-white text-lg leading-none text-primary transition group-open:rotate-45 group-open:border-primary/30 group-open:bg-primary/10">
                      +
                    </span>
                  </summary>
                  <p className="mt-3 max-w-3xl whitespace-pre-line text-sm font-medium leading-7 text-muted-foreground">
                    {faq.answer}
                  </p>
                </details>
              ))}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}
