import Image from "next/image";
import Link from "next/link";
import { joomlaService } from "@/services/joomlaService";
import { getNavigationData } from "@/app/api/navigation/route";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { SampleCategoryGrid } from "@/components/common/SampleCategoryGrid";
import { siteName } from "@/lib/pageHelpers";

/**
 * `/questions` — a real category browser, same as `/free-samples`, NOT a
 * single article (see AGENTS.md §8). Sourced directly from
 * `templates/GAH/html/com_content/category/default_children.php`'s `else`
 * branch (category id 314): a banner with 3 real stat badges, a subject
 * grid over the "Questions" category's real subcategories, a CTA strip, then
 * a "Latest Question & Answers" feed of the most recent articles across all
 * of those subjects. Colors/copy below are read from that file and its
 * `questions.css`, not approximated.
 */
export async function QuestionsIndexPage({ basePath = "/answers" }: { basePath?: string } = {}) {
  const rootAlias = basePath === "/answers" ? "answers" : "questions";
  const [categories, latestQuestions, navigationData] = await Promise.all([
    joomlaService.getQuestionCategories(rootAlias),
    joomlaService.getLatestQuestions(4, rootAlias),
    getNavigationData(),
  ]);

  const dateFormatter = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric" });

  return (
    <div className="min-h-[60vh] bg-white">
      <section
        className="w-full relative overflow-hidden py-8 sm:py-10 px-4 sm:px-6 lg:px-12"
        style={{
          backgroundColor: "#ebe6e3",
          backgroundImage: "url(/images/question-banner.png)",
          backgroundRepeat: "no-repeat",
          backgroundPosition: "left bottom",
          backgroundSize: "contain",
        }}
      >
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row items-center justify-start min-h-[300px] sm:min-h-[340px]">
          {/* Spacer for man image on left side for md+ screens */}
          <div className="hidden md:block w-[32%] lg:w-[35%] shrink-0" />

          {/* Left-aligned text container positioned to the right of the portrait */}
          <div className="w-full md:w-[68%] lg:w-[65%] text-left space-y-3.5 pl-0 md:pl-4">
            <h1 className="text-xl sm:text-2xl md:text-3xl lg:text-[36px] leading-tight font-extrabold text-[#1D1D1D]">
              Expertly Curated <span className="text-[#5C7A36]">Answers</span> To Your{" "}
              <span className="text-[#5C7A36]">Questions</span>
            </h1>
            <p className="text-xs sm:text-sm leading-relaxed text-[#1D1D1D] max-w-2xl font-normal">
              Seek comprehensive assistance with your most challenging homework questions from our extensive library
              of expertly answered questions.Uncover thousands of questions and their corresponding answers across a
              broad spectrum of disciplines.
            </p>

            <ul className="flex flex-wrap items-center justify-start gap-x-8 gap-y-4 pt-3">
              {[
                { icon: "/icons/question-library.svg", number: "5000+", label: "Q&A Library" },
                { icon: "/icons/question-solution.svg", number: "Free", label: "Expert Written Solution" },
                { icon: "/icons/question-experts.svg", number: "4500+", label: "Experts" },
              ].map(({ icon, number, label }) => (
                <li key={label} className="flex items-center gap-3">
                  <Image src={icon} alt="" width={34} height={34} className="w-8 h-8 sm:w-9 sm:h-9 shrink-0" />
                  <div className="text-left">
                    <p className="text-sm sm:text-base font-extrabold text-[#131313] leading-tight">
                      {number}
                    </p>
                    <p className="text-[11px] sm:text-xs text-slate-600 font-medium">{label}</p>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </section>

      <Breadcrumb items={[{ label: basePath.slice(1).charAt(0).toUpperCase() + basePath.slice(2) }]} />

      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pt-6 pb-10">
        {categories.length === 0 ? (
          <p className="text-sm text-slate-500 text-center">No question subjects available right now.</p>
        ) : (
          <SampleCategoryGrid
            categories={categories}
            basePath={basePath}
            searchPlaceholder="What do you want to know?"
            showCount={false}
          />
        )}
      </div>

      <section className="py-6 px-4 text-center" style={{ background: "#F6FFEB" }}>
        <p className="text-lg font-bold" style={{ color: "#1D1D1D" }}>
          <span style={{ color: "#5C7A36" }}>Affordable</span> Answers, <span style={{ color: "#5C7A36" }}>Premium</span>{" "}
          Results!
        </p>
        <p className="text-sm text-slate-600 mt-1 max-w-xl mx-auto">
          Make us your go-to platform for resolving all your academic queries without breaking the bank!
        </p>
        <Link
          href={navigationData.header.cta.orderNowUrl}
          className="inline-block mt-4 rounded px-4 py-2.5 text-xs font-bold uppercase text-white"
          style={{ background: "#f58e0e" }}
        >
          Ask your question
        </Link>
      </section>

      {latestQuestions.length > 0 && (
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
          <h2 className="text-2xl font-bold text-center mb-8" style={{ color: "#1D1D1D" }}>
            Latest Question &amp; Answers
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {latestQuestions.map((q) => (
              <div key={q.id} className="rounded p-4 bg-white" style={{ boxShadow: "0 0 4px 0 rgba(0,0,0,0.25)" }}>
                <Link href={`/${q.alias}`} className="font-bold hover:text-[#5C7A36] transition-colors">
                  {q.title}
                </Link>
                <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs mt-2.5" style={{ color: "#373737" }}>
                  <span>
                    <b>Downloads:</b> {q.downloads.toLocaleString()}
                  </span>
                  <span>
                    <b>Pages:</b> {q.pageCount}
                  </span>
                  <span>
                    <b>Words:</b> {q.wordCount.toLocaleString()}
                  </span>
                  {q.createdAt && (
                    <span>
                      <b>Date:</b> {dateFormatter.format(new Date(q.createdAt))}
                    </span>
                  )}
                </div>
                <p className="text-sm mt-2.5" style={{ color: "#2a2a2a" }}>
                  {q.excerpt}{" "}
                  <Link href={`/${q.alias}`} className="font-bold" style={{ color: "#EF841F" }}>
                    View
                  </Link>
                </p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
