import Link from "next/link";
import { notFound } from "next/navigation";
import { joomlaService } from "@/services/joomlaService";
import { getNavigationData } from "@/app/api/navigation/route";
import { getHomePageData } from "@/app/api/home/route";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { ServiceOrderForm } from "@/components/home/ServiceOrderForm";
import { WriterSpotlightCarousel } from "@/components/common/WriterSpotlightCarousel";
import { ExploreFreeToolsBlock } from "@/components/common/ExploreFreeToolsBlock";
import { displayOnlyCount, hireWriterUrl, resolveImageUrl } from "@/lib/pageHelpers";

/**
 * Individual `/questions/{subject}/{alias}` Q&A article. The live site never
 * shows these answers in full for free — only a short teaser, blurred and
 * cut off under an "Unlock Full Answers Instantly!" overlay, same as every
 * other visitor sees. The generic article renderer this page replaces had
 * no such gate at all, so it was leaking the complete, real paid-answer
 * content (tables, full essay body, references — everything) to anyone who
 * requested the URL. This app has no real unlock/payment flow to connect
 * that button to, so — honestly, not faked — it links to the real customer
 * panel login instead of pretending to unlock anything client-side.
 *
 * Sidebar reuses the same real pieces as `BlogArticlePage`
 * (`ServiceOrderForm` for pricing, the "Explore FREE Tools" list) plus a
 * writer-card list built from the same real `getWriters()` data
 * `FreeToolExpertsList` uses, just laid out with Tailwind here instead of a
 * CSS file — this sidebar is app chrome, not raw Joomla HTML.
 */
export async function QuestionArticlePage({
  subjectAlias,
  alias,
  basePath = "/answers",
}: {
  subjectAlias: string;
  alias: string;
  basePath?: string;
}) {
  const rootAlias = basePath === "/answers" ? "answers" : "questions";
  const [article, navigationData, categories, { data: writers }, orderConfig, pricing, homeData] =
    await Promise.all([
      joomlaService.getArticleBySlug(alias),
      getNavigationData(),
      joomlaService.getQuestionCategories(rootAlias),
      joomlaService.getWriters(6, 0),
      joomlaService.getOrderServiceConfig(),
      joomlaService.getPricingConfig(),
      getHomePageData(),
    ]);

  if (!article || (!article.introtext && !article.fulltext)) {
    notFound();
  }

  const subjectTitle = categories.find((c) => c.alias === subjectAlias)?.title || subjectAlias;
  const writerImages = await Promise.all(writers.map((w) => resolveImageUrl(w.imageUrl)));
  const articleHtml = [article.introtext, article.fulltext]
    .filter(Boolean)
    .join("\n")
    .replace(/\r\n/g, "\n");

  const cpanelUrl = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";
  const uniqueFeatures = [
    "Zero Plagiarism",
    "24*7 Live Support",
    "Unlimited Revisions",
    "Free Plagiarism Report",
    "Money-Back Guarantee",
    "No Privacy Infringement",
  ];
  const sectionLabel = basePath.slice(1).charAt(0).toUpperCase() + basePath.slice(2);

  return (
    <div className="bg-slate-50 min-h-screen">
      <Breadcrumb
        items={[
          { label: sectionLabel, href: basePath },
          { label: subjectTitle, href: `${basePath}/${subjectAlias}` },
          { label: article.title },
        ]}
      />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-8 items-start">
        <article className="min-w-0">
          <h1 className="text-2xl sm:text-3xl font-extrabold text-slate-900 leading-tight mb-6">{article.title}</h1>

          {/* Real literal heading from the live template (`<h2>Answer :</h2>`,
              confirmed against the reference install's own rendered output) —
              not CMS-editable content, just static template chrome that sits
              between the title and the paywalled answer body. */}
          <h2 className="text-lg font-bold text-slate-900 mb-3">Answer :</h2>

          <div className="relative">
            <div
              className="prose prose-green max-w-none text-sm text-slate-700 leading-relaxed max-h-[320px] overflow-hidden blur-[2px] select-none"
              dangerouslySetInnerHTML={{ __html: articleHtml }}
            />
            <div className="absolute inset-0 top-10 flex items-start justify-center bg-gradient-to-b from-transparent via-slate-50/70 to-slate-50">
              <div className="mt-16 bg-white border border-slate-200 rounded-2xl shadow-lg p-6 max-w-sm text-center space-y-3">
                <p className="text-lg font-bold text-slate-900">
                  Unlock Full <span className="text-[#f58e0e]">Answers</span> Instantly!
                </p>
                <p className="text-sm text-slate-500">
                  Access detailed, expert solutions to all your questions with just one click. See the complete
                  answers now!
                </p>
                <a
                  href={`${cpanelUrl}/login`}
                  className="inline-block rounded bg-[#f58e0e] hover:bg-[#e07d0d] text-white font-bold text-sm px-6 py-2.5 transition-colors"
                >
                  Unlock Now
                </a>
              </div>
            </div>
          </div>

          <div
            className="mt-8 rounded-2xl p-6 sm:p-8 text-center"
            style={{ background: "linear-gradient(135deg, #f3fbe9 0%, #e1ecd3 100%)" }}
          >
            <p className="text-xl font-bold text-slate-900">
              Resolve all your doubts in <span className="text-[#5C7A36]">One Place</span>
            </p>
            <p className="mt-2 text-sm text-slate-600 max-w-xl mx-auto">
              We provide expert solutions to your questions. Search for your doubts here and resolve your queries
              smoothly.
            </p>
            <Link
              href={basePath}
              className="mt-4 inline-block rounded bg-[#f58e0e] hover:bg-[#e07d0d] text-white font-bold text-sm px-6 py-2.5 transition-colors"
            >
              Ask Your Question
            </Link>
          </div>

          <p className="mt-8 text-sm text-slate-600 leading-relaxed bg-white border border-slate-200 rounded-xl p-5">
            Often times, students feel unable to work on assignments and think if the academic writing tools can
            help in developing an excellent content. But, if you check out the{" "}
            <Link href="/free-samples" className="text-[#f58e0e] font-semibold">
              Sample
            </Link>{" "}
            on various subjects, it will help you understand all the intricacies of our writing. We have the most
            qualified and skilled assignment writers who can provide the best assignment writing services at the
            most affordable rates. Place your order now for surprising discounts.
          </p>
        </article>

        <aside className="space-y-6 lg:sticky lg:top-6">
          <ServiceOrderForm
            variant="sidebar"
            config={homeData.hero.calculator}
            orderConfig={orderConfig}
            pricing={pricing}
            title="Boost Grades & Leave Stress"
            subtitle="Share Your Requirements Now for Customized Solutions."
          />

          <WriterSpotlightCarousel
            writers={writers}
            images={writerImages}
            subtitle={`For Top ${subjectTitle} Assignment Help`}
            completedOrders={writers.map((w) => displayOnlyCount(w.id, 150, 1400))}
            hireUrls={writers.map((w) => hireWriterUrl(w.name))}
          />

          <div className="rounded-xl bg-white border border-slate-200 shadow-sm p-5">
            <p className="text-sm font-bold text-slate-900 mb-3">Our Unique Features</p>
            <ul className="space-y-2">
              {uniqueFeatures.map((feature) => (
                <li key={feature} className="flex items-center gap-2 text-sm text-slate-700">
                  <img src="/icons/result-right.svg" alt="" className="w-4 h-4 shrink-0" />
                  {feature}
                </li>
              ))}
            </ul>
          </div>

          <ExploreFreeToolsBlock />
        </aside>
      </div>
    </div>
  );
}
