import React from "react";
import Link from "next/link";
import Image from "next/image";
import type { BestDeal, PricingConfig, RelatedService } from "@/services/joomlaService";
import calculatorConstants from "@/data/calculator-constants.json";
import { FreeToolsLottie } from "@/components/common/FreeToolsLottie";
import { ExploreFreeToolsBlock } from "@/components/common/ExploreFreeToolsBlock";
import { StickyBestDeal } from "@/components/common/StickyBestDeal";

/**
 * The Services-page right sidebar. On the live site this whole column is a
 * single Joomla module — "Rightbar Service" (mod_custom id 115, position
 * `user6`), pulled in by service.php as `$custom_rightbar_section` — with two
 * placeholder tokens that PHP substitutes: `service_image`/`offer_code` for
 * the promo strip, and `static_free_feature_rightbar` for the features box.
 *
 * See AGENTS.md "Services-page right sidebar" for where each block's data and
 * markup came from.
 */

interface ServiceSidebarProps {
  orderNowUrl: string;
  /** Article ids/aliases from the article's `related-services` field. */
  relatedServices: RelatedService[];
  /** Real promos from the central `coupons` table. */
  bestDeals: BestDeal[];
  /** Cart URL the "Get Deal" buttons point at, with the promo code appended. */
  cartUrl: string;
  offersUrl: string;
  /** Real site-wide pricing + central currency rates. */
  pricing: PricingConfig | null;
  /** Which `currency_values` row to price in — see CalculatorConfig.priceCountry. */
  priceCountry: string;
}

/** `$_SESSION['order_currency'] . ' ' . round($amt / $_SESSION['selected_price'], 2)`. */
function convertCurrency(amount: number, divisor: number, code: string): string {
  return `${code} ${(Math.round((amount / divisor) * 100) / 100).toFixed(2)}`;
}

// Base amounts exactly as service.php passes them to convertCurrency()
// (`ContentHelper::convertCurrency(5.8 * 50)` and so on).
const FREE_FEATURES = [
  { label: "Topic Creation", amount: 5.8 * 50 },
  { label: "Outline", amount: 14 * 50 },
  { label: "Unlimited Revisions", amount: 31 * 50 },
  { label: "Editing / Proofreading", amount: 42 * 50 },
  { label: "Formatting", amount: 12 * 50 },
  { label: "Bibliography", amount: 11 * 50 },
];
const FREE_FEATURES_TOTAL = 115.8 * 50;

// From the module's `.rightbar_samples` block.
const SAMPLE_LINKS = [
  { label: "Sample of assignment", href: "/free-samples" },
  { label: "Essay samples", href: "/essay-examples" },
  { label: "Course work samples", href: "/coursework-examples" },
  { label: "Case study", href: "/case-study-examples" },
  { label: "Dissertation Samples", href: "/dissertation-examples" },
  { label: "Sample of Thesis", href: "/thesis-examples" },
];

// From the module's `.sidebar-tools-adv` block. "Thesis statement" is the one
// entry whose menu alias differs from the article alias our router resolves
// by (`thesis-statement-generator` targets the `thesis-tool` article), the
// same mismatch handled in the nav's Free Resources list.
const FREE_TOOLS = [
  { label: "AI Humanizer", href: "/ai-humanizer" },
  { label: "AI Essay Writer", href: "/ai-essay-writer" },
  { label: "Essay Typer Tool", href: "/essay-typer" },
  { label: "Plagiarism Checker", href: "/plagiarism-checker" },
  { label: "Paraphrasing Tool", href: "/paraphrasing-tool" },
  { label: "Grammar Checker Tool", href: "/grammar-checker" },
  { label: "Reference Generator", href: "/referencing" },
  { label: "AI homework helper", href: "/ai-homework-helper" },
  { label: "Thesis statement", href: "/thesis-tool" },
  { label: "Dissertation generator", href: "/dissertation-outline-generator" },
  { label: "Summary generator", href: "/summary-generator" },
];

/** The template labels each link `ucwords(str_replace('-', ' ', $alias))`. */
function relatedServiceLabel(alias: string): string {
  return alias
    .split("-")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}

export const ServiceSidebar: React.FC<ServiceSidebarProps> = ({
  orderNowUrl,
  relatedServices,
  bestDeals,
  cartUrl,
  offersUrl,
  pricing,
  priceCountry,
}) => {
  // Same derivation the template uses: selected_price = $currency[1].price / rate.
  const rate = pricing?.currencyRates.find((row) => row.country === priceCountry);
  const usdBase = Number(calculatorConstants.currency["1"].price);
  const selectedPrice = rate ? usdBase / rate.value : usdBase;
  const price = (amount: number) => convertCurrency(amount, selectedPrice, rate?.currency ?? "USD");
  // service.php only renders this block when there's more than one real
  // related service — a bridge fallback used to fill the gap with invented
  // links (one of which 404'd), which is why this doesn't fall back to
  // anything now.
  const displayServices = relatedServices && relatedServices.length > 1 ? relatedServices : [];

  return (
    <aside className="space-y-5">
      {/* Promo strip. On the live site the active variant is fully dynamic
          (`?code=offer_code` + `service_image` from the central `crm_offers`
          table); every seasonal variant in the module is commented out. That
          table isn't on this server, so this uses the module's own
          EXTRA25 image, which is the offer the live page is running. */}
      <a href={`${orderNowUrl}?code=EXTRA25`} className="block">
        <Image
          src="/images/service-offer-strip.png"
          alt="Seasonal offer: up to 56% off with code EXTRA25"
          width={340}
          height={340}
          className="w-full h-auto rounded"
        />
      </a>

      <div className="rightside-topic free-fearure">
        <div className="side_link">
          <p className="title">
            <s className="paid-strike">Paid</s> <span className="green-text">FREE</span> Features
          </p>
          <ul>
            {FREE_FEATURES.map((feature) => (
              <li key={feature.label}>
                <div className="left">{feature.label}</div>
                <div className="right">
                  <span className="fearure-price">{price(feature.amount)}</span>
                </div>
              </li>
            ))}
          </ul>
          <div className="price-box">
            <p className="price-p">Get all these features for</p>
            <p className="price-free">
              <span className="total-price">{price(FREE_FEATURES_TOTAL)}</span>FREE
            </p>
            <div>
              <a href={orderNowUrl} className="button order-btn">
                <span>Let&apos;s Start</span>
              </a>
            </div>
          </div>
        </div>
      </div>

      <div className="rightbar_samples">
        <div className="title">Our Samples</div>
        <div className="sample_list">
          <ul>
            {SAMPLE_LINKS.map((sample) => (
              <li key={sample.href}>
                <Link href={sample.href} className="samples">
                  {sample.label}
                </Link>
              </li>
            ))}
          </ul>
        </div>
      </div>

      <ExploreFreeToolsBlock />

      {/* "Other Services" — Image 2 UI with solid green header bar and NO scroll box */}
      {displayServices.length > 0 && (
        <div className="rightside-topic services">
          <div className="side_link">
            <div className="title">Other Services</div>
            <ul>
              {displayServices.map((related) => (
                <li key={related.id}>
                  <Link href={`/${related.alias}`}>{relatedServiceLabel(related.alias)}</Link>
                </li>
              ))}
            </ul>
          </div>
        </div>
      )}

      {/* "Best Deals" — real promos; `titleHtml` is CMS-authored markup the
          template injects as-is. */}
      {bestDeals.length > 0 && (
        <StickyBestDeal className="best-deal">
          <p className="deal-title">
            <strong>Best </strong>Deals
          </p>
          {bestDeals.map((deal) => (
            <div className="deal-list" key={deal.code}>
              <div className="left" dangerouslySetInnerHTML={{ __html: deal.titleHtml }} />
              <div className="right">
                <p className="promo-txt">Promo code</p>
                <span className="promo-code">{deal.code}</span>
                <a href={`${cartUrl}?code=${encodeURIComponent(deal.code)}`} className="promo-btn">
                  Get Deal
                </a>
              </div>
            </div>
          ))}
          <p className="footer-p footer-p-first">
            That&rsquo;s not all! We have many offers in Store for you. No Matter you are our regular
            customer or a New one, we have Something for All.
          </p>
          <p className="footer-p">Terms &amp; Condition Apply</p>
          <a href={offersUrl} className="order-btn">
            Know More
          </a>
        </StickyBestDeal>
      )}
    </aside>
  );
};
