"use client";

import Image from "next/image";
import { useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import ProgramsMobileSlider from "./ProgramsMobileSlider";
import { withCDN, optimizedImage } from "@/src/lib/utils";
import type { ProgramsPageSection } from "@/src/lib/services/programsPageService";
import ImageLightbox from "../ui/ImageLightbox";
import { scrollToId } from "@/src/lib/utils/scrollToId";

interface InspiringYounMindsProps {
  inspiringMindData?: ProgramsPageSection;
}

const defaultData = {
  id: 1,
  contentTitle: "INSPIRING YOUNG MINDS AROUND THE GLOBE",
  description:
    "Young Engineers offers interactive enrichment programs, immersing students in the joys of hands-on learning. Designed by our dedicated research and development team, our sets enable students to build intriguing machines,models and robots, reinforcing the notion that education can be a thrilling adventure.",
  ctaButtonText: "Get Your Free Ticket",
  mainImage: withCDN("/programs-page/InspiringYoung/IMG_2147%201.png"),

  thumbnails: [
    withCDN("/discover/discover-1.png"),
    withCDN("/discover/discover-2.png"),
    withCDN("/discover/discover-5.png"),
    withCDN("/discover/discover-6.png"),
  ],
};

function parseImages(imagesJson?: string) {
  if (!imagesJson) return null;

  try {
    const images = JSON.parse(imagesJson);

    if (Array.isArray(images) && images.length > 0) {
      return images;
    }

    return null;
  } catch (error) {
    console.warn("[InspiringYounMinds] Failed to parse images:", error);
    return null;
  }
}

export default function InspiringYounMinds({
  inspiringMindData,
}: InspiringYounMindsProps) {
  const apiImages = parseImages(inspiringMindData?.images);

  const finalImages =
    apiImages || [defaultData.mainImage, ...defaultData.thumbnails];

  const currentData = {
    id: 1,
    contentTitle:
      inspiringMindData?.heading || defaultData.contentTitle,
    description:
      inspiringMindData?.description || defaultData.description,
    ctaButtonText:
      inspiringMindData?.ctaButtonText || defaultData.ctaButtonText,
    mainImage: finalImages[0],
    allImages: finalImages,
  };

  const allImages = currentData.allImages;

  const [currentSlide, setCurrentSlide] = useState(0);
  const [mainImage, setMainImage] = useState(currentData.mainImage);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const [slideDirection, setSlideDirection] = useState<"next" | "prev">(
    "next"
  );

  /*
   * MOBILE SLIDER ANIMATION
   *
   * Next:
   * - New image comes from right
   * - Old image goes to left
   *
   * Previous:
   * - New image comes from left
   * - Old image goes to right
   *
   * Images slightly scale down while moving.
   */
  const mobileSlideVariants = {
    enter: (direction: "next" | "prev") => ({
      x: direction === "next" ? "100%" : "-100%",
      scale: 0.82,
      opacity: 1,
    }),

    center: {
      x: 0,
      scale: 1,
      opacity: 1,
    },

    exit: (direction: "next" | "prev") => ({
      x: direction === "next" ? "-100%" : "100%",
      scale: 0.82,
      opacity: 1,
    }),
  };

  const nextSlide = () => {
    setSlideDirection("next");

    setCurrentSlide((prev) => {
      return (prev + 1) % allImages.length;
    });
  };

  const prevSlide = () => {
    setSlideDirection("prev");

    setCurrentSlide((prev) => {
      return (prev - 1 + allImages.length) % allImages.length;
    });
  };

  const touchStartX = useRef<number | null>(null);
  const touchStartY = useRef<number | null>(null);

  const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
    const touch = e.touches[0];

    touchStartX.current = touch.clientX;
    touchStartY.current = touch.clientY;
  };

  const handleTouchEnd = (e: React.TouchEvent<HTMLDivElement>) => {
    if (
      touchStartX.current === null ||
      touchStartY.current === null
    ) {
      return;
    }

    const touch = e.changedTouches[0];

    const deltaX = touch.clientX - touchStartX.current;
    const deltaY = touch.clientY - touchStartY.current;

    touchStartX.current = null;
    touchStartY.current = null;

    /*
     * Ignore vertical swipes
     */
    if (Math.abs(deltaY) > Math.abs(deltaX)) {
      return;
    }

    const SWIPE_THRESHOLD = 50;

    /*
     * Ignore small movements
     */
    if (Math.abs(deltaX) < SWIPE_THRESHOLD) {
      return;
    }

    /*
     * Swipe left = next
     * Swipe right = previous
     */
    if (deltaX < 0) {
      nextSlide();
    }

    if (deltaX > 0) {
      prevSlide();
    }
  };

  return (
    <section
      className="
        relative w-full overflow-hidden z-20
        py-24
        xl:h-[1000px]
        2xl:h-[1130px]
        h-[1060px]
        sm:h-[1020px]
        md:h-[660px]
        lg:h-[810px]
        xl:h-[1130px]
        max-[400px]:h-[1050px]
        -mt-[240px]
        md:-mt-[100px]
        lg:-mt-[300px]
        xl:-mt-[250px]
        inspiring-block
      "
    >
      <div className="absolute inset-0 w-full h-full -z-10">
        <Image
          src="https://yefranchisees.b-cdn.net/frontend/home/bg-desktop.png"
          alt="Curved background"
          fill
          className="object-fit object-top hidden lg:block"
          priority
        />

        <Image
          src="https://yefranchisees.b-cdn.net/frontend/home/bg-desktop.png"
          alt="Curved background for tablet"
          fill
          className="object-cover object-top hidden md:block lg:hidden"
          priority
        />

        <Image
          src="https://yefranchisees.b-cdn.net/frontend/home/bg-mobile.png"
          alt="Curved background for mobile"
          fill
          className="object-cover object-top block md:hidden"
          priority
        />
      </div>

      <div
        className="
          max-w-[1300px] mx-auto w-full flex flex-col
          md:flex-row gap-4 md:gap-4 lg:gap-6
          items-center lg:items-start
          mt-[-80]
          lg:mt-20
          xl:mt-36
          2xl:mt-17
          md:mt-16
          2xl:py-20
          px-4 md:px-9 lg:px-18 xl:px-0
        "
      >
        {/* MOBILE HEADING */}
        <h2
          className="
            md:hidden
            text-[30px]
            leading-[1]
            font-[700]
            text-[#0097DC]
            uppercase
            mb-4
            mt-25
          "
        >
          {currentData.contentTitle}
        </h2>

        {/* MOBILE SLIDER */}
        <div className="block md:hidden w-full">
          <div
            className="
              flex items-center justify-center
              gap-4
              mt-0
              touch-pan-y
            "
            onTouchStart={handleTouchStart}
            onTouchEnd={handleTouchEnd}
          >
            {/* PREVIOUS BUTTON */}
            <button
              onClick={prevSlide}
              className="flex-shrink-0"
              aria-label="Previous slide"
              type="button"
            >
              <Image
                src={withCDN("/arrow left.png")}
                alt="Previous"
                width={23}
                height={23}
                className="object-contain"
              />
            </button>

            {/* MOBILE IMAGE */}
            <div
              className="
                relative
                flex-1
                h-[170px]
                max-w-[340px]
                sm:max-w-[100%]
                sm:h-[270px]
                rounded-2xl
                overflow-hidden
                inspire-young-mind-mobile-image
              "
            >
              <AnimatePresence
                initial={false}
                custom={slideDirection}
              >
                <motion.img
                  key={currentSlide}
                  src={allImages[currentSlide]}
                  alt={`Slide ${currentSlide + 1}`}
                  custom={slideDirection}
                  variants={mobileSlideVariants}
                  initial="enter"
                  animate="center"
                  exit="exit"
                  transition={{
                    duration: 0.55,
                    ease: [0.22, 1, 0.36, 1],
                  }}
                  className="
                    absolute
                    inset-0
                    w-full
                    h-full
                    object-cover
                    cursor-pointer
                    select-none
                  "
                  draggable={false}
                  onClick={() =>
                    setLightboxIndex(currentSlide)
                  }
                />
              </AnimatePresence>
            </div>

            {/* NEXT BUTTON */}
            <button
              onClick={nextSlide}
              className="flex-shrink-0"
              aria-label="Next slide"
              type="button"
            >
              <Image
                src={withCDN("/arrow right.png")}
                alt="Next"
                width={23}
                height={23}
                className="object-contain"
              />
            </button>
          </div>
        </div>

        {/* LEFT - CONTENT */}
        <div
          className="
            w-full
            md:flex-1
            flex flex-col
            gap-6
            md:w-[50%]
            lg:w-[40%]
            xl:w-[40%]
          "
        >
          <div className="w-full 2xl:w-[470px] xl:mt-[-50px]">
            <h2
              className="
                hidden
                md:block
                md:text-md
                text-[30px]
                leading-[1]
                xl:text-[50px]
                xl:leading-[55px]
                xl:w-[90%]
                font-[700]
                text-[#0097DC]
                uppercase
                mb-4
                mt-1
                md:mt-[-30]
                lg:mt-[-1]
              "
            >
              {currentData.contentTitle}
            </h2>

            <p
              className="
                text-base
                md:text-sm
                text-[18px]
                font-[300]
                text-[#58585A]
                leading-none
                xl:text-[22px]
                md:text-[16px]
                text-gray-60
                leading-relaxed
              "
            >
              {currentData.description}
            </p>
          </div>

          <button
            onClick={() => {
              scrollToId("program-from");
            }}
            className="
              inline-flex
              items-center
              text-[18px]
              md:text-[15px]
              lg:text-[18px]
              2xl:text-[24px]
              xl:h-[60px]
              cursor-pointer
              uppercase
              justify-center
              gap-2
              md:gap-2
              bg-[#0097DC]
              hover:bg-[#0097DC]
              hover:shadow-[10px_14px_14px_#0000000D]
              active:bg-[#0084C1]
              text-white
              font-medium
              text-center
              leading-tight
              px-4
              py-2
              md:px-5
              md:py-3
              rounded-full
              transition
              md:w-fit
              w-full
              max-[767px]:min-h-[50px]
              max-[360px]:text-[14px]
            "
          >
            <img
              src={withCDN("/ticket.png")}
              alt="Ticket Icon"
              className="w-5 h-5 object-contain shrink-0"
            />

            {currentData.ctaButtonText}
          </button>
        </div>

        {/* RIGHT - MAIN IMAGE AND THUMBNAILS */}
        <div
          className="
            hidden
            md:flex
            md:flex-col
            lg:flex-row
            w-auto
            gap-2
            md:w-[50%]
            lg:w-[60%]
            xl:w-[59%]
            md:mt-[-20px]
            lg:mt-0
          "
        >
          {/* MAIN IMAGE */}
          <div
            className="
              w-[340px]
              h-[269px]
              md:h-[250px]
              lg:h-[269px]
              2xl:w-[604px]
              2xl:h-[464px]
              md:w-[100%]
              lg:w-[450px]
              lg:h-[324px]
              rounded-[32px]
              overflow-hidden
              bg-gray-200
              flex-shrink-0
              young-mind-image
            "
          >
            <img
              src={optimizedImage(mainImage, 1280)}
              alt="Main content"
              className="
                w-full
                h-full
                object-cover
                cursor-pointer
              "
              onClick={() =>
                setLightboxIndex(
                  Math.max(
                    0,
                    allImages.indexOf(mainImage)
                  )
                )
              }
            />
          </div>

          {/* THUMBNAILS */}
          <div
            className="
              flex
              w-auto
              lg:flex-col
              gap-2
              xl:gap-5
              flex-shrink-0
              justify-between
            "
          >
            {currentData.allImages.map(
              (thumbnail, index) => {
                const isSelected =
                  thumbnail === mainImage;

                return (
                  <div
                    key={index}
                    className="
                      w-[80px]
                      h-[60px]
                      md:w-[86px]
                      md:h-[70px]
                      lg:h-[75px]
                      xl:w-[130px]
                      xl:h-[100px]
                      rounded-xl
                      overflow-hidden
                      relative
                      cursor-pointer
                      flex-shrink-0
                      inspire-thumbnail
                    "
                    onClick={() =>
                      setMainImage(thumbnail)
                    }
                  >
                    <img
                      src={optimizedImage(thumbnail, 384)}
                      alt={`Thumbnail ${index + 1}`}
                      className={`
                        w-full
                        h-full
                        object-cover
                        transition
                        ${
                          isSelected
                            ? "brightness-75 scale-[1.02]"
                            : "brightness-100"
                        }
                      `}
                    />

                    {isSelected && (
                      <div
                        className="
                          absolute
                          inset-0
                          flex
                          items-center
                          justify-center
                          bg-[#34343480]
                        "
                      />
                    )}
                  </div>
                );
              }
            )}
          </div>
        </div>
      </div>

      {/* LIGHTBOX */}
      <ImageLightbox
        images={allImages}
        index={lightboxIndex}
        onClose={() => setLightboxIndex(null)}
      />
    </section>
  );
}