import type { Metadata } from "next";
import { CircleHelp } from "lucide-react";
import { BreadcrumbSection } from "@/components/BreadcrumbSection";
import { serverApiBaseUrl } from "@/lib/api-url";
import { FaqContent, type FaqCategoryEntry } from "@/app/faq/FaqContent";
import { JsonLd, breadcrumbJsonLd, faqJsonLd } from "@/lib/seo";

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

export const metadata: Metadata = {
  title: "Frequently Asked Questions",
  description:
    "Find answers to common questions about Ride N Revive doorstep car service, bike service, booking, pricing, and support.",
  alternates: {
    canonical: "/faq",
  },
  openGraph: {
    title: "FAQs | Ride N Revive",
    description:
      "Answers to common questions about Ride N Revive doorstep vehicle service and support.",
    url: "/faq",
  },
};

async function getFaqs() {
  try {
    const response = await fetch(`${serverApiBaseUrl}/api/faqs`, {
      cache: "no-store",
    });

    if (!response.ok) {
      return [];
    }

    const data = (await response.json()) as { faqs?: Faq[] };
    return data.faqs ?? [];
  } catch {
    return [];
  }
}

function groupFaqs(faqs: Faq[]) {
  return faqs.reduce<Record<string, Faq[]>>((groups, faq) => {
    groups[faq.category] = [...(groups[faq.category] ?? []), faq];
    return groups;
  }, {});
}

export default async function FaqPage() {
  const faqs = await getFaqs();
  const groupedFaqs = groupFaqs(faqs);
  const structuredFaqs = faqJsonLd(faqs);
  const categoryEntries: FaqCategoryEntry[] = Object.entries(groupedFaqs).map(
    ([category, items]) => ({ category, items }),
  );

  return (
    <>
      <JsonLd
        data={[
          breadcrumbJsonLd([
            { name: "Home", path: "/" },
            { name: "FAQ", path: "/faq/" },
          ]),
          ...(structuredFaqs ? [structuredFaqs] : []),
        ]}
      />
      <BreadcrumbSection
        currentPage="FAQ"
        title="Frequently asked questions"
        lead="Quick answers about booking, doorstep service, vehicle care, pricing, and support."
      />

      <section className="bg-slate-50 font-['Space_Grotesk']">
        <div className="mx-auto max-w-7xl px-4 py-14 md:px-6 2xl:py-24">
          {faqs.length === 0 ? (
            <div className="mx-auto max-w-3xl rounded-md border border-dashed border-border bg-white p-10 text-center shadow-sm">
              <div className="mx-auto grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <CircleHelp className="h-6 w-6" />
              </div>
              <h2 className="mt-5 text-2xl font-black tracking-tight text-foreground">
                FAQs are coming soon
              </h2>
              <p className="mt-3 text-sm font-semibold leading-relaxed text-muted-foreground">
                We are organizing the most common questions here. For now, contact Ride N Revive
                directly and our team will help with the next step.
              </p>
            </div>
          ) : (
            <FaqContent categories={categoryEntries} />
          )}
        </div>
      </section>
    </>
  );
}
