"use client";

import { useState, useRef, useEffect } from "react";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";
import { detailHref } from "@/src/lib/utils/detailHref";

import Image from "next/image";
import { withCDN } from "@/src/lib/utils";
import { Swiper, SwiperSlide } from "swiper/react";
import { Mousewheel } from "swiper/modules";
import type { Swiper as SwiperType } from "swiper";
import type { WorkshopSection, Activity } from "@/src/lib/services/workshopService";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { fetchWorkshopActivities } from "@/src/lib/actions/workshopAction";
import { mapActivitiesToWorkshopCards } from "@/src/lib/utils/workshopMapper";
import WorkshopCardSkeleton from "../ui/skeletons/WorkshopCardSkeleton";
import "swiper/css";

type WorkshopCard = {
  id: string;
  title: string;
  subtitle: string;
  description: string;
  createdFor: string;
  ageRange: string;
  ageText: string;
  durationHeading: string;
  durationText: string;
  lessonDuration: string;
  lessonsTotal: string;
  ribbon: string;
  borderColor: string;
  iconSrc: string;
  imageSrc: string;
  parentActivitiesId?: string | null;
  language?: string | null;
  AiGradientStart?: string;
  AiGradientEnd?: string;
};

const FALLBACK_WORKSHOPS: WorkshopCard[] = [
  {
    id: "SUMMER_CAMP",
    title: "Camps",
    subtitle: "Welcome to CREATIVE STEM CAMPS FOR YOUNG INNOVATORS",
    description:
      "where kids learn science and engineering by building moving models. Through real-world themes like physics, energy, and motion, they discover how things work — all while having fun outdoors.",
    createdFor: "Created for kids",
    ageRange: "1-5",
    ageText: "Age",
    durationHeading: "Duration",
    durationText: "",
    lessonDuration: "Full-day",
    lessonsTotal: "program over 5 days",
    ribbon: withCDN("/Workshop/bg%20%284%29.png"),
    borderColor: "#95C11F",
    AiGradientStart: "#95C11F",
    AiGradientEnd: "#226B20",
    iconSrc: withCDN("/workshop-logo/logo_camps.svg"),
    imageSrc: withCDN("/Workshop/photo%20(12).png"),
  },
  {
    id: "BIRTHDAY_PARTIES",
    title: "Birthday parties",
    subtitle: "MAKE YOUR SPECIAL DAY UNFORGETTABLE",
    description:
      "Celebrate with creativity and discovery! Our birthday workshops turn your party into a hands-on engineering adventure — where fun meets innovation, and every guest becomes a young creator.",
    createdFor: "Created for kids",
    ageRange: "6–10",
    ageText: "Age",
    durationHeading: "Duration",
    durationText: "min",
    lessonDuration: "120",
    lessonsTotal: "",
    ribbon: withCDN("Workshop/bg%20%285%29.png"),
    borderColor: "#F49800",
    iconSrc: withCDN("/workshop-logo/logo_birthday.svg"),
    imageSrc: withCDN("/Workshop/photo%20(11).png"),
  },
  {
    id: "BUILD_UP",
    title: "Build UP",
    subtitle: "LEARNING THROUGH CREATIVITY AND CONNECTION",
    description:
      "A unique program designed for children with special needs that encourages personal growth through teamwork and mechanical exploration. Each session builds confidence, curiosity, and joy.",
    createdFor: "Created for kids",
    ageRange: "2-5",
    ageText: "grades with diverse needs",
    durationHeading: "Duration",
    durationText: "min",
    lessonDuration: "75",
    lessonsTotal: "",
    ribbon: withCDN("/Workshop/bg%20%286%29.png"),
    borderColor: "#3A82C5",
    iconSrc: withCDN("/workshop-logo/logo_build_up.svg"),
    imageSrc: withCDN("/Workshop/photo%20(10).png"),
  },
  {
    id: "PRO",
    title: "PRO",
    subtitle: "INNOVATION MEETS TEAMBUILDING",
    description:
      "A dynamic workshop for organizations and professionals, designed to strengthen collaboration and problem-solving through hands-on engineering challenges. Build, create, and grow together.",
    createdFor: "Created for",
    ageRange: "professionals, corporate teams & organizations",
    ageText: "",
    durationHeading: "Duration",
    durationText: "min",
    lessonDuration: "120",
    lessonsTotal: "",
    ribbon: withCDN("/Workshop/bg%20%287%29.png"),
    borderColor: "#0B253C",
    iconSrc: withCDN("/workshop-logo/logo_pro.svg"),
    imageSrc: withCDN("/Workshop/photo%20(9).png"),
  },
  {
    id: "GOLDEN_AGE",
    title: "Golden age",
    subtitle: "Where CREATIVITY KNOWS NO AGE",
    description:
      "This inspiring workshop invites seniors to explore the joy of building, imagination, and motion. Through guided activities, participants enhance motor skills, memory, and social connection — while having fun.",
    createdFor: "Created for adults",
    ageRange: "55+",
    ageText: "& intergenerational groups",
    durationHeading: "Duration",
    durationText: "min",
    lessonDuration: "90",
    lessonsTotal: "",
    ribbon: withCDN("/Workshop/bg%20%288%29%20%281%29.png"),
    borderColor: "#DDBD48",
    iconSrc: withCDN("/workshop-logo/logo_golden_age.svg"),
    imageSrc: withCDN("/Workshop/photo%20(8)%20(2).png"),
  },
];

function WorkshopArticle({ workshop }: { workshop: WorkshopCard }) {
  // Translations link to their base/parent activity; LanguageAwareLink adds the
  // lang/franchiseeId params automatically.
  const learnMoreHref = detailHref("/workshops", workshop.parentActivitiesId || workshop.id, workshop.title);

  return (
    <article
      className="
        relative
        bg-white
        rounded-[32px]
        shadow-md
        md:h-[320px]
        xl:h-[360px]
        flex flex-col md:flex-row
        border
        overflow-visible
        workshop-article
        lg:mt-[40px]
        max-[767px]:overflow-hidden
      "
      style={{ borderColor: workshop.borderColor }}
      id={`workshop-${workshop.title}`} 
    >
      {/* 🔹 MOBILE HEADER : mini ribbon + text OUTSIDE ribbon */}
      <div className="md:hidden flex items-center gap-2 px-3 pt-1">
        {/* small gradient ribbon with only logo */}
        <div
          className="
          relative 
          w-[120px] h-[161px]
          flex items-center justify-center
          overflow-hidden
        "
          style={{
            backgroundImage: `url(${workshop.ribbon})`,
            backgroundSize: "cover",
            backgroundPosition: "center bottom", // ⬅️ IMPORTANT
            top: "-4px",
          }}
        >
          <div className="relative w-[95px] h-[95px] rounded-[50%] mt-[-24] bg-white max-[360px]:w-[72px] max-[360px]:h-[72px]">
            {workshop.iconSrc ? (
              <Image
                src={workshop.iconSrc}
                alt={workshop.title}
                fill
                className="object-contain w-[80px] h-[64px]"
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-gray-300">
                <span className="text-[10px]">No Logo</span>
              </div>
            )}
          </div>
        </div>

        {/* text block OUTSIDE ribbon on white */}
        <div className="flex-1 flex flex-col justify-between text-[11px] leading-snug text-gray-800 mt-[-4]">
          <div>
            <h3
              className="
              text-[30px] md:text-[25px] lg:text-[54px]
              font-bold uppercase leading-none mb-2
            "
              style={{ color: workshop.borderColor }}
            >
              {workshop.title}
            </h3>
          </div>
          
        </div>
      </div>

      {/* 🔹 DESKTOP RIBBON : original tall gradient with all details inside */}
      <div className="md:w-[145px] xl:w-[220px] hidden md:flex md:flex-col md:px-0">
        <div
          className="
            absolute
            top-[-2]
            w-[200px] md:left-4 2xl:left-8 md:rounded-tl-[10px] xl:rounded-tl-[0px]
            h-[400px]
            md:w-[140px] md:h-[370px]
            xl:w-[190px] xl:h-[425px]
            bg-cover bg-center bg-no-repeat
            flex flex-col items-center justify-start text-white gap-3
            overflow-visible workshop-ribbon
          "
          style={{
            backgroundImage: `url(${workshop.ribbon})`,
          }}
        >
          <div className="flex flex-col items-center gap-2 mt-3 w-[80%] xl:w-[70%]">
            <div className="relative w-14 h-14 md:w-28 md:h-28 md:w-[100px] md:h-[100px] xl:w-[142px] xl:h-[142px] shrink-0 bg-white rounded-[50%] flex items-center justify-center wrksp-logo-box">
              {workshop.iconSrc ? (
                <Image
                  src={workshop.iconSrc}
                  alt={workshop.title}
                  fill
                  className="object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-gray-300">
                  <span className="text-xs">No Logo</span>
                </div>
              )}
            </div>

            <div className="text-xs md:text-sm leading-snug w-full mt-2 range-box">
              <p className="opacity-80  text-[11px] lg:text-[16px] w-full">
                {workshop.createdFor}
              </p>
              
              {workshop.ageRange && (
                <span
                  className={`font-bold range-t ${
                    workshop.ageRange.length > 12
                      ? "text-[14px] md:text-[16px] lg:text-[17px] xl:text-[18px] leading-[22px]"
                      : "text-base md:text-lg text-[14px] lg:text-[20px] xl:text-[30px] leading-[35px]"
                  }`}
                >
                  {workshop.ageRange}
                </span>
              )}
              {workshop.ageText && (
                <span className="text-[14px] age-t xl:text-[16px]"> {workshop.ageText}</span>
              )}
            </div>
            {workshop.lessonDuration && (
              <div className="w-full text-xs md:text-lg leading-snug mt-2 range-box">
                <p className="opacity-80 text-[14px] lg:text-[16px] w-full whitespace-nowrap leading-tight">
                  {workshop.durationHeading}
                </p>
                <span className="font-bold md:text-lg text-[14px] lg:text-[20px] xl:text-[30px] leading-tight">
                  {workshop.lessonDuration}
                </span>
                <span className="text-[14px] time leading-[14px] xl:text-[16px]"> {workshop.durationText}</span>
                <p className="opacity-80 mt-1 text-[14px] leading-[14px] xl:text-[16px]">
                  {workshop.lessonsTotal}
                </p>
              </div>
            )}
          </div>

        </div>
      </div>

      {/* 🔹 CENTER CONTENT */}
      <div
        className="
        flex-1
        px-5 
        md:px-6 md:py-2 lg:px-8 xl:px-1 2xl:px-8
        flex flex-col
        
        md:pr-[280px] lg:pr-[260px] xl:pr-[540px] 2xl:pr-[580px]
        min-h-[350px] md:max-h-[358px]  workshop-content
      "
      >
        <div className="flex-1 pr-2  mt-[px] lg:mb-[18px]">
          <div className="min-h-full flex flex-col justify-center">
            <h3
              className="
            text-[30px] md:text-[30px] xl:text-[50px]
            font-bold uppercase leading-tight xl:leading-none hidden md:block
    "
              style={{ color: workshop.borderColor }}
            >
              {workshop.title}
            </h3>

            <div className="mt-2">
              <h3
                className="
                text-[18px] md:text-[18px] xl:text-[20px] 2xl:text-[20px]
                uppercase leading-tight text-[#58585A]
                "
              >
                {workshop.subtitle.split(" ").map((word, index) => (
                 <span key={index}>
                   {index > 0 && " "}

                   {word.toUpperCase() === "AI" ? (
                     <span
                       className="inline-flex items-center justify-center text-white px-3 py-[1px] rounded-[10px] text-[20px] xl:text-[18px] xl:leading-[28px] leading-[30px] max-[330px]:text-[17px] max-[330px]:leading-[24px] max-[330px]:px-2"
                      style={{
                      background: `linear-gradient(
                       265deg,
                       ${workshop.AiGradientStart},
                       ${workshop.AiGradientEnd}
                       )`,
                       }}
                     >
                       {word}
                     </span>
                   ) : (
                     word
                   )}
                 </span>
               ))}
              </h3>
              
              <div className="block md:hidden border-b border-t border-[#CACACA] mt-2 mb-3">
                <div className="flex flex-row py-3 gap-4">
            <div className="mr-2 left-box w-[40%]">
              <p className="opacity-80 text-[12px] hidden md:block">{workshop.createdFor}</p>
              <p className="opacity-80 text-[12px] block md:hidden">Created for</p>
              <div className="flex items-end gap-2">
              {workshop.ageRange && (
                <span
                  className={`font-bold range-t ${
                    workshop.ageRange.length > 12
                      ? "text-[16px] leading-[20px]"
                      : "text-[25px] leading-[26px]"
                  }`}
                  style={{ color: workshop.borderColor }}>
                  {workshop.ageRange}
                </span>
              )}{" "}
              {workshop.ageText && (
                <p className="text-[12px] age-t" style={{ color: workshop.borderColor }}>{workshop.ageText}</p>
              )}
              </div>
            </div>
            {workshop.lessonDuration && (
              <div className="text-left">
                <p className="opacity-80 text-[12px]">{workshop.durationHeading}</p>
                <div className="flex items-end gap-2">
                <span
                  className="font-bold text-[25px] leading-[26px]"
                  style={{ color: workshop.borderColor }}
                >
                  {workshop.lessonDuration.replace(/\s*Days?/i, "")}
                </span>

                <span
                  className="font-bold text-[12px] leading-[20px]"
                  style={{ color: workshop.borderColor }}
                >
                  {workshop.lessonDuration.match(/Days?/i)?.[0]}
                </span>{" "}
                <span className="text-[12px] time2 block" style={{ color: workshop.borderColor }}>{workshop.durationText}</span>
                </div>

                <p className="opacity-80 mt-1 text-[12px]" style={{ color: workshop.borderColor }}>
                  {workshop.lessonsTotal}
                </p>
              </div>
            )}
          </div>
              </div>


              <p
                className="
                mt-3 2xl:mt-4 text-[16px] md:text-[14px] xl:text-[16px] min-[1600px]:!text-[16px]
                leading-relaxed text-[#58585A] max-w-[480px] xl:max-w-[600px] 2xl:max-w-[700px] text-[#58585A]
                break-words workshop-description md:pr-3 md:overflow-y-auto md:scroll-thin md:h-[90px]"
              >
                {workshop.description}
              </p>
            </div>

            {/* give extra bottom padding so button isn't clipped when scrolled to bottom */}
            <div className="mt-4 ">
              <LanguageAwareLink
                href={learnMoreHref}
                className="
                inline-flex items-center gap-2 w-full xl:py-2 xl:px-1
                rounded-full border border-[#00AEEF]
                px-2 py-2 text-[15px] xl:text-[15px] font-regular tracking-[1px]
                bg-[#0097DC] text-white h-[45px]
                transition-colors w-40 md:w-50 lg:w-50 xl:w-60 2xl:w-60 justify-center
                cursor-pointer hover:bg-[#0097DC] hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] active:shadow-[10px_14px_14px_#0000000D]
              "
              >
                <Image
                  src={withCDN("/programs-page/AllPrograms/Vector.svg")}
                  alt="arrow"
                  width={26}
                  height={26}
                  className="transition-all"
                />
                <span>LEARN MORE</span>
              </LanguageAwareLink>
            </div>
          </div>
        </div>
      </div>

      {/* 🔹 RIGHT IMAGE (unchanged) */}
      <div
        className="
          relative
          w-[98%]
          sm:w-[100%]
          sm:right-2
          right-0
          mx-auto
          mt-2
          xl:right-8
          h-[217px]
          rounded-[30px]
          overflow-hidden
          md:absolute md:top-1/2 md:right-2 md:-translate-y-1/2
          md:w-[257px] md:mx-0 md:mt-0 mb-1 sm:mb-4
          md:h-[360px] lg:h-[350px]
          xl:w-[506px] xl:h-[403px]  workshop-image
        "
      >
        {workshop.imageSrc ? (
          <Image
            src={workshop.imageSrc}
            alt={workshop.title}
            fill
            className="object-cover"
          />
        ) : (
          <div className="w-full h-full bg-gray-100 flex items-center justify-center text-gray-400">
            <span>No Image</span>
          </div>
        )}
      </div>
    </article>
  );
}

interface AllWorkshopProps {
  allWorkshopData?: WorkshopSection;
  generalSettings?: any;
  activities?: Activity[];
  isLoading?: boolean;
}

export default function AllWorkshop({
  allWorkshopData,
  generalSettings,
  activities = [],
  isLoading = false
}: AllWorkshopProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [visibleCount, setVisibleCount] = useState(5);
  const [workshops, setWorkshops] = useState<WorkshopCard[]>([]);
  const swiperRef = useRef<SwiperType | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);

  const { currentLanguage } = useLanguage();

  useEffect(() => {
    if (Array.isArray(activities) && activities.length > 0) {
      const mappedWorkshops = mapActivitiesToWorkshopCards(activities);

      if (mappedWorkshops && mappedWorkshops.length > 0) {
        // Wrap paths with CDN logic
        const workshopsWithCDN = mappedWorkshops.map(workshop => ({
          ...workshop,
          ribbon: (workshop.ribbon && !workshop.ribbon.startsWith('http')) ? withCDN(workshop.ribbon) : workshop.ribbon,
          iconSrc: (workshop.iconSrc && !workshop.iconSrc.startsWith('http')) ? withCDN(workshop.iconSrc) : workshop.iconSrc,
          // Only wrap with CDN if it's a relative path
          imageSrc: (workshop.imageSrc && workshop.imageSrc.startsWith('http')) ? workshop.imageSrc : withCDN(workshop.imageSrc),
        }));

        setWorkshops(workshopsWithCDN);
      } else {
        // Fallback to empty or static if mapping fails
        setWorkshops([]);
      }
    } else if (!isLoading) {
      // Fallback to static data if loading is finished and no data arrived
      setWorkshops(
        FALLBACK_WORKSHOPS.map(workshop => ({
          ...workshop,
          ribbon: withCDN(workshop.ribbon),
          iconSrc: withCDN(workshop.iconSrc),
          imageSrc: withCDN(workshop.imageSrc),
        }))
      );
    }
  }, [activities, isLoading]);

  // Removed old internal fetching effects

  // Get heading and showMoreText from API
  const heading = allWorkshopData?.heading || "ALL YE WORKSHOPS";
  const showMoreText = allWorkshopData?.showMoreText || "See more";

  const goToSlide = (index: number) => {
    if (swiperRef.current) {
      swiperRef.current.slideTo(index);
    }
  };

  const handleShowMore = () => {
    setVisibleCount((prev) => Math.min(prev + 3, workshops.length));
  };

  const handleSlideChange = (swiper: SwiperType) => {
    // Use realIndex for loop mode to get the actual program index
    const realIndex = swiper.realIndex ?? swiper.activeIndex;
    setCurrentIndex(realIndex);
  };

  // Get visible Workshop for desktop/tablet
  const visibleWorkshop = workshops.slice(0, visibleCount);
  const hasMore = visibleCount < workshops.length;

  return (
    <section
      ref={containerRef}
      className="
        relative w-full
        overflow-visible
        mt-0
        sm:-mt-150
        h-fit
        xl:-mt-35
        md:-mt-35
        lg:-mt-35
        z-30
        pt-32 pb-24 xl:pb-[30px]
      "
    >
      {/* Curved Background */}
      <div className="absolute inset-0 w-full h-full -z-10">
        <Image
          src={withCDN("/programs-page/AllPrograms/allPrograms.svg")}
          alt="Curved background"
          fill
          className="object-cover object-top hidden lg:block"
          priority
        />

        {/* Tablet */}
        <Image
          src={withCDN("/allProgramsTab.svg")}
          alt="Curved background for tablet"
          fill
          className="object-cover object-top hidden md:block lg:hidden"
          priority
        />

        {/* Mobile */}
        <Image
          src={withCDN("/programs-page/AllPrograms/allPrograms.svg")}
          alt="Curved background for mobile"
          fill
          className="object-cover object-top block md:hidden"
          priority
        />
      </div>

      {/* Content on top of curve */}
      <div className="relative z-20 max-w-[1300px] mx-auto w-full px-4 md:px-10 lg:px-18 xl:px-0">
        {/* Heading */}
        <h2 className="text-[30px] xl:text-[50px] text-[#58585A] md:text-[32px] font-[700] tracking-wide uppercase leading-none mb-[47px] mt-[-10]">
          {heading}
        </h2>

        {/* ✅ Mobile Slider */}
        <div className="md:hidden">
          <div className="max-w-full mx-auto">
            {isLoading ? (
              <div className="space-y-6">
                {[1, 2].map((idx) => (
                  <WorkshopCardSkeleton key={idx} />
                ))}
              </div>
            ) : (
              <Swiper
                modules={[Mousewheel]}
                onSwiper={(swiper) => {
                  swiperRef.current = swiper;
                }}
                onSlideChange={handleSlideChange}
                slidesPerView={1}
                spaceBetween={20}
                loop={false}
                mousewheel={{
                  forceToAxis: true,
                  sensitivity: 1,
                  releaseOnEdges: true,
                }}
                grabCursor={true}
                className="all-programs-swiper"
              >
                {workshops.map((workshop) => (
                  <SwiperSlide key={workshop.id}>
                    <WorkshopArticle workshop={workshop} />
                  </SwiperSlide>
                ))}
              </Swiper>
            )}
          </div>

          {/* Custom Dots Navigation */}
          {!isLoading && (
            <div className="flex justify-center mb-6 mt-1">
              {workshops.map((workshop, idx) => (
                <button
                  key={workshop.id}
                  onClick={() => goToSlide(idx)}
                  aria-label={`Go to ${workshop.title}`}
                  className="w-[40px] h-[40px] flex items-center justify-center"
                >
                  <span
                    className={`
                      w-[16px] h-[16px] rounded-full transition-all duration-200
                      ${idx === currentIndex ? "bg-[#00AEEF]" : "bg-[#00AEEF]/40"}
                    `}
                  />
                </button>
              ))}
            </div>
          )}
        </div>

        {/* ✅ Tablet & Desktop – original stacked cards */}
        <div className="space-y-10 md:space-y-20 xl:space-y-20 hidden md:block">
          {isLoading ? (
            [1, 2, 3].map((idx) => (
              <WorkshopCardSkeleton key={idx} />
            ))
          ) : (
            <>
              {visibleWorkshop.map((workshop) => (
                <WorkshopArticle key={workshop.id} workshop={workshop} />
              ))}
              {hasMore && (
                <div className="flex justify-center my-8 md:my-10 lg:my-0">
                  <button
                    onClick={handleShowMore}
                    className="text-[#00AEEF] text-sm font-light tracking-wide uppercase hover:underline transition-all cursor-pointer"
                  >
                    {showMoreText.toUpperCase()}
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </section>
  );
}
