"use client";

import { Fragment, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import BookAnAppointmentModal from "@/components/CommonComponent/BookAppointmentModal";
import WhiteArrow from "../../../../../public/images/white-arrow.svg";
import { OurPricingProps } from "@/types/aesthetic-offers-bulle";

export default function OurPricing({ title, heading, cta_text, description, price_cards, showCTA }: OurPricingProps) {
  useEffect(() => {
    const isFromHome = sessionStorage.getItem("scrollToPricing") === "true";
    const hasHash = window.location.hash === "#pricing";

    if (isFromHome || hasHash) {
      sessionStorage.removeItem("scrollToPricing");
      setTimeout(() => {
        document.getElementById("pricing")?.scrollIntoView({ behavior: "smooth" });
      }, 500);
    }
  }, []);

  const formatSubtitle = (text?: string) => text?.trim().toUpperCase() || "";

  const formatAmount = (amt?: string) => {
    if (!amt) return null;

    const cleaned = amt.trim().replace(/,\s*$/, "");

    if (cleaned.toLowerCase().startsWith("from")) {
      const val = cleaned.slice(4).trim();

      return (
        <div className="mb-6 flex items-baseline justify-center gap-1.5">
          <span className="text-[14px] font-semibold text-[#334D72]">From</span>
          <span className="text-[32px] font-medium leading-none text-[#00204F] md:text-[40px]">{val}</span>
        </div>
      );
    }

    return <div className="mb-6 text-center text-[32px] font-bold text-[#00204F] md:text-[40px]">{cleaned}</div>;
  };

  return (
    <section className="scroll-mt-20 mb-10 bg-[#F2F4F6] py-10 md:py-24 xl:py-30" id="pricing">
      <div className="container">
        <div className="mb-10 text-center md:mb-16">
          <span className="mb-3 block text-[12px] font-medium uppercase tracking-[0.5px] text-[#334D72] md:text-[14px]">{formatSubtitle(title)}</span>
          <h2 className="mb-4 text-[32px] font-medium leading-tight text-[#00204F] md:text-[44px] xl:text-[48px]">{heading}</h2>
          <p className="mx-auto hidden text-[20px] leading-relaxed text-[#334D72] md:block md:max-w-[548px]">{description}</p>
        </div>

        <div className="grid grid-cols-12 items-end gap-6 lg:gap-8">
          {price_cards?.map((card, index) => {
            const isRecommended = card.tag === "Recommended";
            const isFourthCard = index === 3;

            const cardHeight =
              index === 0 ? "h-[auto] xl:h-[370px]" :
              index === 1 ? "h-[auto] xl:h-[406px]" :
              index === 2 ? "h-[auto] xl:h-[330px]" :
              "h-[auto]";

            const defaultCtaText = [
              "Choose Aesthetic Medicine",
              "Choose Cosmetic Surgery",
              "Choose Cosmetic Treatments",
              "Book a free consultation",
            ][index];

            const mobileCtaText = card.cta_text || defaultCtaText;

            const cardContent = (
              <article className={`${isFourthCard ? "w-full" : "col-span-12 md:col-span-6 xl:col-span-4"} ${cardHeight} relative flex flex-col md:overflow-hidden rounded-[24px] border border-[#CCD2DC] bg-white px-4 pb-4 transition-shadow duration-300 hover:shadow-lg md:px-6 md:pb-6 ${isRecommended ? "border-[#00D8F6] pt-[49px] ring-1 ring-[#00D8F6]/20 xl:pt-[60px]" : "pt-4 md:pt-6"}`}>
                {isRecommended && (
                  <div className="absolute left-0 right-0 top-0 bg-[#76F5FF] px-3 py-2 text-center text-[12px] font-bold leading-[140%] text-[#00204F]">
                    {card.tag}
                  </div>
                )}

                {isFourthCard && card.card_image && (
                  <div className="mb-3 flex justify-center">
                    <div className="flex h-[72px] w-[72px] items-center justify-center rounded-full bg-[#E8F1FF]">
                      <Image src={card.card_image} width={40} height={40} alt="" className="object-contain" />
                    </div>
                  </div>
                )}

                <h3 className={`mb-4 block text-center text-[20px] font-bold tracking-[0.5px] text-[#00204F] ${isFourthCard ? "normal-case" : "uppercase"}`}>
                  {card.title}
                </h3>

                {isFourthCard && card.description && (
                  <p className="mb-6 text-center text-[14px] leading-[140%] text-[#334D72]">{card.description}</p>
                )}

                {!isFourthCard && formatAmount(card.amount)}

                <div className="mb-6 h-px w-full shrink-0 bg-[#E5E9ED]" />

                <div className="flex flex-col gap-4 mb-6 md:mb-0">
                  {card.points?.map((pt, pIdx) => (
                    <div key={pIdx} className="flex items-start gap-3">
                      <div className="mt-0.5 shrink-0">
                        <Image src="/images/green-check.svg" width={20} height={20} alt="Green check" />
                      </div>
                      <p className="text-[14px] font-medium leading-normal text-[#334D72] md:text-[15px]">{pt?.point?.trim() || ""}</p>
                    </div>
                  ))}
                </div>

                {mobileCtaText && (
                  <Link
                    href={card.cta_link || "#"}
                    className={`mt-auto flex w-full shrink-0 items-center justify-center gap-1 rounded-[8px] border border-[#1718FF] px-4 py-2 text-center text-[16px] font-bold leading-[140%] md:hidden ${isRecommended ? "bg-[#1718FF] text-white" : "bg-white text-[#1718FF]"}`}
                  >
                    {mobileCtaText}
                  </Link>
                )}
              </article>
            );

            if (isFourthCard) {
              return <div key={index} className="col-span-12 block md:hidden">{cardContent}</div>;
            }

            return <Fragment key={index}>{cardContent}</Fragment>;
          })}
        </div>

        {showCTA && (
          <div className="mt-12 flex justify-center md:mt-16">
            <BookAnAppointmentModal buttonText={cta_text} buttonBgClass="bg-[#1718F5]" buttonTextClass="text-white" arrowIcon={WhiteArrow} className="w-auto" />
          </div>
        )}
      </div>
    </section>
  );
}