import type { Metadata } from "next";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { API_CONFIG, API_ENDPOINTS } from "@/core/api/config/config";

export const metadata: Metadata = {
  title: "Frequently Asked Questions | Ameera Holidays",
  description:
    "Find answers to common questions about Ameera Holidays's services, bookings, payments, cancellations, and more. Get help with vehicle bookings, hotels, and travel packages.",
  openGraph: {
    title: "Frequently Asked Questions | Ameera Holidays",
    description:
      "Find answers to common questions about Ameera Holidays's services, bookings, payments, cancellations, and more. Get help with vehicle bookings, hotels, and travel packages.",
    type: "website",
  },
  twitter: {
    card: "summary_large_image",
    title: "Frequently Asked Questions | Ameera Holidays",
    description:
      "Find answers to common questions about Ameera Holidays's services, bookings, payments, cancellations, and more. Get help with vehicle bookings, hotels, and travel packages.",
  },
};

type FAQItem = {
  id: number;
  question: string;
  answer: string;
};

type FAQSection = {
  id: number;
  title: string;
  items: FAQItem[];
};

type ApiFaqItem = {
  id?: number;
  sort_order?: number;
  status?: string;
  question?: string;
  answer?: string;
};

type ApiFaqCategory = {
  id?: number;
  name?: string;
  faq_details?: ApiFaqItem[];
};

type ApiFaqResponse = {
  statusCode?: number;
  success?: boolean;
  data?: {
    data?: ApiFaqCategory[];
  };
};

const FAQ_API_URL = `${API_CONFIG.BASE_URL}${API_ENDPOINTS.FAQ_CATEGORIES}`;

function isNonEmptyString(value: unknown): value is string {
  return typeof value === "string" && value.trim().length > 0;
}

function parseFaqResponse(payload: unknown): FAQSection[] {
  const response = payload as ApiFaqResponse;

  if (
    response?.statusCode !== 200 ||
    response?.success !== true ||
    !Array.isArray(response?.data?.data)
  ) {
    return [];
  }

  return response.data.data
    .filter(
      (
        category
      ): category is Required<Pick<ApiFaqCategory, "id" | "name">> &
        ApiFaqCategory =>
        typeof category?.id === "number" && isNonEmptyString(category?.name)
    )
    .map((category) => {
      const items = Array.isArray(category.faq_details)
        ? category.faq_details
            .filter(
              (
                item
              ): item is Required<
                Pick<ApiFaqItem, "id" | "question" | "answer">
              > &
                ApiFaqItem =>
                typeof item?.id === "number" &&
                isNonEmptyString(item?.question) &&
                isNonEmptyString(item?.answer) &&
                item?.status === "active"
            )
            .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
            .map((item) => ({
              id: item.id,
              question: item.question.trim(),
              answer: item.answer.trim(),
            }))
        : [];

      return {
        id: category.id,
        title: category.name.trim(),
        items,
      };
    })
    .filter((section) => section.items.length > 0);
}

async function getFaqSections(): Promise<FAQSection[]> {
  try {
    const response = await fetch(FAQ_API_URL, { next: { revalidate: 300 } });
    if (!response.ok) {
      return [];
    }

    const payload = (await response.json()) as unknown;
    return parseFaqResponse(payload);
  } catch {
    return [];
  }
}

export default async function FAQPage() {
  const sections = await getFaqSections();
  const hasFaqData = sections.length > 0;

  return (
    <main className="min-h-screen bg-[#f7f9fb]">
      <section className="w-full bg-gradient-to-br from-secondary-foreground/5 to-secondary-foreground/10">
        <div className="w-full px-4 py-10 md:px-10 md:py-14 lg:px-16">
          <Link href="/" className="inline-block">
            <Button
              variant="ghost"
              size="sm"
              className="-ml-2 mb-8 gap-2 text-base text-slate-900"
            >
              <ArrowLeft className="h-4 w-4" />
              Back to Home
            </Button>
          </Link>

          <header className="mx-auto max-w-4xl py-2 text-center md:py-6">
            <h1 className="text-balance text-4xl font-bold tracking-tight text-slate-950 md:text-6xl">
              Frequently Asked{" "}
              <span className="frontend-text-gradient">Questions</span>
            </h1>
            <p className="mx-auto mt-5 max-w-3xl text-lg leading-relaxed text-slate-700 md:text-xl md:leading-10">
              Find answers to the most common questions about using ameera
              holidays. If you can't find what you're looking for, feel free to
              contact our support team.
            </p>
          </header>
        </div>
      </section>

      <section className="container mx-auto p-4 md:p-6 lg:p-8">
        <div className="space-y-10">
          {hasFaqData ? (
            sections.map((section) => (
              <section key={section.id} className="space-y-4">
                <h2 className="text-2xl font-bold tracking-tight frontend-text-gradient md:text-2xl">
                  {section.title}
                </h2>
                <div className="space-y-3">
                  {section.items.map((item) => (
                    <details
                      key={item.id}
                      className="group rounded-2xl border border-slate-200 bg-slate-100/70 shadow-sm [&_summary::-webkit-details-marker]:hidden [&_summary::marker]:hidden"
                    >
                      <summary className="flex cursor-pointer items-center gap-3 px-5 py-5 text-left text-base font-semibold text-slate-900 md:text-lg">
                        <span className="w-5 shrink-0 text-center text-xl font-normal leading-none frontend-text-gradient group-open:hidden">
                          +
                        </span>
                        <span className="hidden w-5 shrink-0 text-center text-xl font-normal leading-none frontend-text-gradient group-open:block">
                          -
                        </span>
                        <span>{item.question}</span>
                      </summary>
                      <div className="px-12 pb-5 text-[15px] leading-7 text-slate-700 md:text-base">
                        {item.answer}
                      </div>
                    </details>
                  ))}
                </div>
              </section>
            ))
          ) : (
            <section className="rounded-2xl border border-slate-200 bg-white p-8 text-center shadow-sm">
              <h2 className="text-2xl font-bold tracking-tight text-slate-900">
                No data found
              </h2>
              <p className="mx-auto mt-3 max-w-2xl text-base leading-relaxed text-slate-700">
                We could not find any FAQ records right now. Please try again
                shortly.
              </p>
            </section>
          )}

          <section className="rounded-2xl border border-secondary-foreground/20 bg-gradient-to-br from-secondary-foreground/5 to-secondary-foreground/10 p-8">
            <h2 className="mb-3 text-2xl font-bold tracking-tight text-slate-900">
              Still Have Questions?
            </h2>
            <p className="mb-6 max-w-2xl text-base leading-relaxed text-slate-700">
              If you couldn&apos;t find the answer you were looking for, our
              support team is here to help you 24/7.
            </p>
            <div className="flex flex-wrap gap-4">
              <Link href="/contact-us">
                <Button size="lg" className="frontend-btn">
                  Contact Support
                </Button>
              </Link>
              <Link href="/">
                <Button size="lg" variant="outline">
                  Back to Home
                </Button>
              </Link>
            </div>
          </section>
        </div>
      </section>
    </main>
  );
}
