import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Search } from "lucide-react";
import { joomlaService } from "@/services/joomlaService";
import { getNavigationData } from "@/app/api/navigation/route";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { ListingPagination } from "@/components/common/ListingPagination";
import { QuestionSubjectFilter } from "@/components/common/QuestionSubjectFilter";
import { StarRating } from "@/components/common/StarRating";
import {
  displayOnlyCount,
  hireWriterUrl,
  LISTING_PAGE_SIZE,
  resolveImageUrl,
  siteName,
} from "@/lib/pageHelpers";

/** `/questions/[subject]` — real Q&A articles within one Questions subject matching the live template layout. */
export async function QuestionsSubjectPage({
  subjectAlias,
  page,
  basePath = "/answers",
}: {
  subjectAlias: string;
  page: number;
  basePath?: string;
}) {
  const rootAlias = basePath === "/answers" ? "answers" : "questions";
  const [
    { data: questions, total, categoryTitle },
    categories,
    { data: sidebarWriters },
    navigationData,
  ] = await Promise.all([
    joomlaService.getQuestionArticles(subjectAlias, LISTING_PAGE_SIZE, (page - 1) * LISTING_PAGE_SIZE, rootAlias),
    joomlaService.getQuestionCategories(rootAlias),
    joomlaService.getWriters(3, 0),
    getNavigationData(),
  ]);

  if (total === 0 && !categoryTitle) notFound();

  const sidebarWriterImages = await Promise.all(sidebarWriters.map((writer) => resolveImageUrl(writer.imageUrl)));
  const displayTitle = categoryTitle || subjectAlias;
  const sectionLabel = basePath.slice(1).charAt(0).toUpperCase() + basePath.slice(2);

  return (
    <div className="min-h-[60vh] bg-white">
      {/* Banner Section */}
      <section className="text-center py-8 px-4 sm:px-6 lg:px-8 bg-[#ebe6e3]">
        <div className="max-w-4xl mx-auto space-y-3">
          <h1 className="text-2xl sm:text-4xl font-bold text-[#1D1D1D]">
            Feeling Trapped in a Question Loop? Pave the Way Out of Puzzles
          </h1>
          <p className="text-sm sm:text-base text-slate-700 max-w-3xl mx-auto leading-relaxed">
            Curious minds thrive on questions but it can get puzzling sometimes. But need not to worry! Just pick your subject, we&apos;ll help you with all your questions. Don&apos;t let confusion stop you – get your academic answers today!
          </p>
        </div>
      </section>

      <Breadcrumb items={[{ label: sectionLabel, href: basePath }, { label: displayTitle }]} />

      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-8 items-start">
          {/* Main Left Column */}
          <div className="space-y-6">
            <h2 className="text-xl sm:text-2xl font-bold text-slate-900">
              Explore All Our <span className="text-[#f58e0e]">{displayTitle}</span> Solutions Now !
            </h2>

            {/* Filter and Search Bar */}
            <QuestionSubjectFilter categories={categories} currentSubjectAlias={subjectAlias} basePath={basePath} />

            {/* Questions List */}
            {questions.length === 0 ? (
              <div className="text-center py-10 rounded-xl border border-dashed border-slate-300 p-8">
                <p className="text-base font-semibold text-slate-700">Oops, empty here!</p>
                <p className="text-sm text-slate-500 mt-1">
                  No questions found for this subject. Click{" "}
                  <Link href={basePath} className="text-[#5C7A36] font-bold underline">
                    here
                  </Link>{" "}
                  to explore more subjects.
                </p>
              </div>
            ) : (
              <div className="space-y-4">
                {questions.map((q) => (
                  <div
                    key={q.id}
                    className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm hover:shadow-md hover:border-[#5C7A36]/40 transition-all space-y-2.5"
                  >
                    <h2 className="text-base sm:text-lg font-bold text-slate-900 leading-snug">
                      <Link href={`${basePath}/${subjectAlias}/${q.alias}`} className="hover:text-[#5C7A36] transition-colors">
                        {q.title}
                      </Link>
                    </h2>

                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-500 font-medium">
                      <span>
                        <strong className="text-slate-700">Downloads:</strong> {q.downloads.toLocaleString()}
                      </span>
                      <span>
                        <strong className="text-slate-700">Pages:</strong> {q.pageCount}
                      </span>
                      <span>
                        <strong className="text-slate-700">Words:</strong> {q.wordCount.toLocaleString()}
                      </span>
                    </div>

                    <p className="text-sm text-slate-600 leading-relaxed line-clamp-3">{q.excerpt}</p>

                    <div className="pt-1">
                      <Link
                        href={`${basePath}/${subjectAlias}/${q.alias}`}
                        className="inline-flex items-center gap-1 font-bold text-sm text-[#f58e0e] hover:underline"
                      >
                        View <ArrowLeft className="w-3.5 h-3.5 rotate-180" />
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <ListingPagination basePath={`${basePath}/${subjectAlias}`} page={page} total={total} />
          </div>

          {/* Right Sidebar */}
          <aside className="space-y-6 lg:sticky lg:top-6">
            {/* Offer Strip */}
            <a
              href={`${navigationData.header.cta.orderNowUrl}?code=EXTRA25`}
              className="block overflow-hidden rounded-xl shadow-sm hover:opacity-95 transition-opacity"
            >
              <Image
                src="/images/service-offer-strip.png"
                alt="Offer Banner - Extra 25% Off"
                width={340}
                height={340}
                className="w-full h-auto rounded-xl"
              />
            </a>

            {/* Expert Writers */}
            <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm space-y-4">
              <div>
                <p className="font-bold text-base text-slate-900 leading-tight">4500+ Experts Writer</p>
                <p className="text-xs text-slate-500 font-medium mt-0.5">
                  For Top {displayTitle} Assignment Help
                </p>
              </div>

              <ul className="divide-y divide-slate-100">
                {sidebarWriters.map((writer, idx) => (
                  <li key={writer.id} className="py-3 first:pt-0 last:pb-0 flex items-center gap-3">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={sidebarWriterImages[idx]}
                      alt={writer.name}
                      className="w-12 h-12 rounded-full object-cover shrink-0 border border-slate-200"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-bold text-slate-900 truncate">{writer.name}</p>
                      <div className="my-0.5">
                        <StarRating score={writer.rating ?? 5.0} />
                      </div>
                      <p className="text-xs text-slate-500">
                        {displayOnlyCount(writer.id, 150, 1400)} - Completed Orders
                      </p>
                    </div>
                    <a
                      href={hireWriterUrl(writer.name)}
                      className="shrink-0 rounded bg-[#5C7A36] hover:bg-[#4E6C2F] text-white text-xs font-bold px-3 py-1.5 transition-colors"
                    >
                      Hire Now
                    </a>
                  </li>
                ))}
              </ul>

              <Link
                href="/writers"
                className="block text-center rounded-lg border border-[#5C7A36] text-[#5C7A36] hover:bg-[#5C7A36] hover:text-white font-bold text-xs py-2.5 transition-colors"
              >
                View All Writers
              </Link>
            </div>

            {/* Rating & Order Section */}
            <div className="rounded-xl border border-slate-200 bg-white p-5 text-center shadow-sm space-y-2">
              <p className="font-bold text-lg text-slate-900">Order Your Assignment</p>
              <p className="text-xs text-slate-500 italic">and see your grades improving...</p>
              <div className="pt-2 text-xs text-slate-600 space-y-1">
                <p className="font-semibold text-slate-700">300K+ Satisfied Students.</p>
                <p>
                  Rated <span className="font-bold text-[#5C7A36]">4.8/5</span>
                </p>
                <p>
                  Based On Overall <span className="font-bold text-[#5C7A36]">5087</span> Reviews.
                </p>
              </div>
              <div className="pt-2">
                <Link
                  href={navigationData.header.cta.orderNowUrl}
                  className="block w-full rounded-lg bg-[#f58e0e] hover:bg-[#e47d00] text-white font-bold text-sm py-2.5 transition-colors shadow-sm"
                >
                  Order Now
                </Link>
              </div>
            </div>

            {/* Our Unique Features */}
            <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm space-y-3">
              <p className="font-bold text-sm text-slate-900 pb-2 border-b border-slate-100">
                Our Unique Features
              </p>
              <ul className="text-xs text-slate-700 space-y-2 font-medium">
                {[
                  "24/7 Customer Support",
                  "100% Customer Satisfaction",
                  "No Privacy Infringement",
                  "Quick Services",
                  "Subject Experts",
                  "Innovative Documents",
                ].map((feature) => (
                  <li key={feature} className="flex items-center gap-2">
                    <span className="w-4 h-4 rounded-full bg-green-100 text-[#5C7A36] flex items-center justify-center text-[10px] font-bold">
                      ✓
                    </span>
                    {feature}
                  </li>
                ))}
              </ul>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}
