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 { ExploreFreeToolsBlock } from "@/components/common/ExploreFreeToolsBlock";
import { WriterSpotlightCarousel } from "@/components/common/WriterSpotlightCarousel";
import { SampleToc } from "@/components/samples/SampleToc";
import { SampleDownloadGate } from "@/components/samples/SampleDownloadGate";
import { SampleShareSection } from "@/components/samples/SampleShareSection";
import { ServiceOrderForm } from "@/components/home/ServiceOrderForm";
import { RelatedSamplesCarousel } from "@/components/samples/RelatedSamplesCarousel";
import { displayOnlyCount, extractSampleToc, hireWriterUrl, resolveImageUrl, splitSampleContent } from "@/lib/pageHelpers";

/**
 * Individual `/free-samples/{category}/{alias}` sample assignment page.
 * Displays the sample header, university details grid (University, Unit No,
 * Level, Pages/Words, Paper Type, Course Code, Downloads), a real
 * Table-of-Content box built from the article's own `<h2>` headings, the
 * question/answer or brief content (gated the same way the live site gates
 * it — a short visible lead, the rest clipped behind an email-capture
 * overlay), and the right sidebar.
 */
export async function SampleArticlePage({
  subjectAlias,
  alias,
  basePath = "/free-samples",
}: {
  subjectAlias: string;
  alias: string;
  basePath?: string;
}) {
  const rootAlias = basePath === "/answers" ? "answers" : "free-samples";
  const [article, navigationData, categories, { data: writers }, orderConfig, pricing, homeData, relatedRes] =
    await Promise.all([
      joomlaService.getArticleBySlug(alias),
      getNavigationData(),
      joomlaService.getSampleCategories(rootAlias),
      joomlaService.getWriters(6, 0),
      joomlaService.getOrderServiceConfig(),
      joomlaService.getPricingConfig(),
      getHomePageData(),
      joomlaService.getSampleArticles(subjectAlias || "business-assignment-help", 10, 0),
    ]);

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

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

  const { items: tocItems, html: articleHtml } = extractSampleToc(rawArticleHtml);
  const { visible: visibleHtml, hidden: hiddenHtml } = splitSampleContent(articleHtml);

  const plainText = articleHtml.replace(/<[^>]*>/g, " ");
  const wordCount = plainText.trim().split(/\s+/).filter(Boolean).length;
  const pageCount = Math.max(1, Math.round(wordCount / 250));

  const uniqueFeatures = [
    "Zero Plagiarism",
    "24*7 Live Support",
    "Unlimited Revisions",
    "Free Plagiarism Report",
    "Money-Back Guarantee",
    "No Privacy Infringement",
  ];

  const relatedSamples = (relatedRes?.data || []).filter((sample) => sample.alias !== article.alias);
  const cpanelUrl = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";
  const loginUrl = `${cpanelUrl}/login`;
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://www.globalassignmenthelp.com";
  const pageUrl = `${siteUrl}${basePath}/${subjectAlias || "business-assignment-help"}/${article.alias}`;
  const rootLabel = basePath === "/answers" ? "Answers" : "Samples";

  return (
    <div className="bg-slate-50 min-h-screen">
      <Breadcrumb
        items={[
          { label: rootLabel, href: basePath },
          { label: subjectTitle, href: subjectAlias ? `${basePath}/${subjectAlias}` : basePath },
          { 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 bg-white rounded-2xl border border-slate-200 p-6 sm:p-8 shadow-sm">
          <h1 className="text-2xl sm:text-3xl font-extrabold text-slate-900 leading-tight mb-6">
            {article.title}
          </h1>

          {/* Details Table — real `.tablePractice` markup/styling (border,
              no background tint, University centered on its own row, then
              two 3-column bordered rows), copied from `sample-details.css`
              rather than the earlier invented green card. */}
          <div className="border border-slate-300 shadow-[0_0_15px_-8px_rgba(0,0,0,0.2)] mb-5 text-sm">
            {article.university && (
              <p className="text-center py-1.5 border-b border-slate-300">
                <span className="text-slate-500">University: </span>
                <span className="font-semibold text-slate-900">{article.university}</span>
              </p>
            )}
            <div className="flex flex-wrap">
              <div className="w-1/2 sm:w-[28%] px-2.5 py-1.5 border-t border-r border-slate-300">
                <span className="text-slate-500">Unit No: </span>
                <span className="font-semibold text-slate-900">{article.unitNo || "N/A"}</span>
              </div>
              <div className="w-1/2 sm:w-[40%] px-2.5 py-1.5 border-t sm:border-r border-slate-300">
                <span className="text-slate-500">Level: </span>
                <span className="font-semibold text-slate-900">{article.academicLevel || "Post Graduate/University"}</span>
              </div>
              <div className="w-full sm:w-[32%] px-2.5 py-1.5 border-t border-slate-300">
                <span className="text-slate-500">Pages: </span>
                <span className="font-semibold text-slate-900">{pageCount}</span>
                {" / "}
                <span className="text-slate-500">Words </span>
                <span className="font-semibold text-slate-900">{wordCount.toLocaleString()}</span>
              </div>
              <div className="w-1/2 sm:w-[28%] px-2.5 py-1.5 border-t border-r border-slate-300">
                <span className="text-slate-500">Paper Type: </span>
                <span className="font-semibold text-slate-900">{article.paperType || "Assignment"}</span>
              </div>
              <div className="w-1/2 sm:w-[40%] px-2.5 py-1.5 border-t sm:border-r border-slate-300">
                <span className="text-slate-500">Course Code: </span>
                <span className="font-semibold text-slate-900">{article.courseCode || "N/A"}</span>
              </div>
              <div className="w-full sm:w-[32%] px-2.5 py-1.5 border-t border-slate-300">
                <span className="text-slate-500">Downloads: </span>
                <span className="font-semibold text-slate-900">{(article.hits ?? 42).toLocaleString()}</span>
              </div>
            </div>
          </div>

          {/* Table of Content, built from the article's own headings */}
          <SampleToc items={tocItems} />

          {article.organisationSelected && (
            <div className="mb-5 text-base font-semibold text-slate-900">
              Organization Selected : <span className="font-bold text-[#5C7A36]">{article.organisationSelected}</span>
            </div>
          )}

          {/* Question Section, only for samples that actually carry real Q&A content */}
          {article.questionHtml && (
            <div className="mb-8 rounded-xl bg-slate-50 border border-slate-200 p-5">
              <h2 className="text-lg font-bold text-[#5C7A36] mb-3">Question :</h2>
              <div
                className="prose prose-green max-w-none text-sm text-slate-700 leading-relaxed"
                dangerouslySetInnerHTML={{ __html: article.questionHtml }}
              />
              <h2 className="text-lg font-bold text-[#5C7A36] mt-5">Answer :</h2>
            </div>
          )}

          {/* Visible lead, then the same clipped/gated remainder the live site shows a logged-out visitor */}
          <div className="space-y-4">
            <div
              className="prose prose-green max-w-none text-sm text-slate-700 leading-relaxed"
              dangerouslySetInnerHTML={{ __html: visibleHtml }}
            />
            {hiddenHtml && <SampleDownloadGate hiddenHtml={hiddenHtml} loginUrl={loginUrl} />}
          </div>

          {hiddenHtml && <SampleShareSection pageUrl={pageUrl} />}

          {hiddenHtml && (
            <a
              href={loginUrl}
              className="block w-fit mx-auto mt-6 rounded bg-[#f58e0e] hover:bg-[#e07d0d] text-white font-bold text-base px-10 py-3 transition-colors"
            >
              Download Full Sample
            </a>
          )}

          <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>

        {/* Right Sidebar */}
        <aside className="space-y-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>

      {/* Latest Related Free-samples Carousel */}
      <RelatedSamplesCarousel samples={relatedSamples} subjectAlias={subjectAlias} />
    </div>
  );
}
