"use client";

import { useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import Image from "next/image";
import { withCDN } from "@/src/lib/utils";
import { slugFallback } from "@/src/lib/programSlugFallback";

interface SlideItem {
  id: number;
  image: string;
  text: string;
  title: string;
  logoImage?: string;
  age?: string;
}

interface ProgramsSliderFooterProps {
  bottomSliders?: any;
  slides?: SlideItem[];
}

const defaultSlides: SlideItem[] = [
  {
    id: 1,
    image: withCDN("/Program-detail/algo-buddy/pct%20(2).png"),
    logoImage: withCDN("/program-logo/logo_algo_buddy.svg"),
    age: "4-6",
    text: "Unlock the power of wind with perfectly coded sequences!",
    title: "Fan Robot",
  },
  {
    id: 2,
    image: withCDN("/Program-detail/algoc/footer/Goal%20Hitter%201.png"),
    logoImage: withCDN("/program-logo/logo_algo_c.svg"),
    age: "13-18",
    text: "Reading distance, reacting in commands, and striking with precision - Technology of the perfect hit!",
    title: "Goal Hitter",
  },
  {
    id: 3,
    image: withCDN("/Program-detail/Big-builders/footer/goose%201%20(1).png"),
    logoImage: withCDN("/program-logo/logo_big_builders.svg"),
    age: "4-6",
    text: "Let's fly together, as the birds show us the way on their migration journey!",
    title: "Bird's Migration",
  },
  {
    id: 4,
    image: withCDN("/Program-detail/footer/accordion%20robot%201.png"),
    logoImage: withCDN("/program-logo/logo_bricks_chalenge.svg"),
    age: "6-10",
    text: "The ratchet mechanism ensures my robot moves forward exclusively, without turning back!",
    title: "Accordion Robot",
  },
  {
    id: 5,
    image: withCDN("/Program-detail/algo-play/pct-5.png"),
    logoImage: withCDN("/program-logo/logo_algo_play.svg"),
    age: "6-10",
    text: "Coding seamlessly orchestrates multiple transmission systems, enhancing their efficiency and adaptability.",
    title: "Fly Away",
  },
  {
    id: 6,
    image: withCDN(
      "/Program-detail/galileo%20technic/footer/Steamroller%201.png"
    ),
    logoImage: withCDN("/program-logo/logo_galileo_technic.svg"),
    age: "7-10",
    text: "Harnessing asymmetry and centrifugal force, the steamroller vibrates to smooth and compact the road surface efficiently!",
    title: "Steamroller",
  },
  {
    id: 7,
    image: withCDN(
      "/Program-detail/smartivo/Smartivo%20spotter_3%201.png"
    ),
    logoImage: withCDN("/program-logo/logo_smartivo.svg"),
    age: "4-6",
    text: "It’s a cosmic mission! Smartivo’s Distance Sensor lights up through event-based coding whenever a satellite is detected.",
    title: "Satellite Spotting Mission",
  },
  {
    id: 8,
    image: withCDN("/Program-detail/smartivo/zombie%201.png"),
    logoImage: withCDN("/program-logo/logo_robo_toys.svg"),
    age: "9-12",
    text: "Watch the Zombie shuffle through commands, mastering interruptions and lighting up the night!",
    title: "Zombie",
  },
];

export default function ProgramsSliderFooter({
  bottomSliders,
  slides,
}: ProgramsSliderFooterProps) {
  /* =========================================================
     SLIDER DATA
  ========================================================= */

  const parsedSliders = useMemo(() => {
    const base = slides && slides.length > 0 ? slides : defaultSlides;

    let apiSliders: any[] = [];

    if (Array.isArray(bottomSliders)) {
      apiSliders = bottomSliders;
    } else if (bottomSliders?.sliders) {
      try {
        apiSliders =
          typeof bottomSliders.sliders === "string"
            ? JSON.parse(bottomSliders.sliders)
            : bottomSliders.sliders;
      } catch (e) {
        console.error("Failed to parse bottomSliders", e);
      }
    }

    if (Array.isArray(apiSliders)) {
      apiSliders = apiSliders.filter(
        (s) =>
          s &&
          (s.program_id ||
            s.program_slug ||
            s.robot_image ||
            (s.tag && s.tag.toString().trim()) ||
            (s.title && s.title.toString().trim()))
      );
    }

    if (!Array.isArray(apiSliders) || apiSliders.length === 0) {
      return base;
    }

    return apiSliders.map((apiSlide, index) => {
      const fallback = base[index] || base[0] || ({} as SlideItem);

      const bySlug = slugFallback(apiSlide?.program_slug);

      return {
        id: fallback.id ?? index + 1,

        image:
          apiSlide?.robot_image ||
          bySlug?.image ||
          fallback.image,

        logoImage:
          apiSlide?.program_logo ||
          bySlug?.logoImage ||
          "",

        age: apiSlide?.age || "",

        title: apiSlide?.tag || "",

        text: apiSlide?.title || "",
      } as SlideItem;
    });
  }, [bottomSliders, slides]);

  /* =========================================================
     PATH
  ========================================================= */

  const pathname = usePathname();

  const isProgramInnerPage =
    pathname.startsWith("/programs/") &&
    pathname !== "/programs";

  /* =========================================================
     SLIDER STATE
  ========================================================= */

  const [currentIndex, setCurrentIndex] = useState(0);

  /* =========================================================
     TOUCH STATE
  ========================================================= */

  const [touchStart, setTouchStart] =
    useState<number | null>(null);

  const [touchEnd, setTouchEnd] =
    useState<number | null>(null);

  /* =========================================================
     AUTOPLAY HOVER
  ========================================================= */

  const [isHovered, setIsHovered] = useState(false);

  /* =========================================================
     CURRENT SLIDE
  ========================================================= */

  const slide =
    parsedSliders[currentIndex] ||
    parsedSliders[0] ||
    defaultSlides[0];

  /* =========================================================
     NEXT
  ========================================================= */

  const next = () => {
    if (parsedSliders.length <= 1) return;

    setCurrentIndex((current) =>
      current === parsedSliders.length - 1
        ? 0
        : current + 1
    );
  };

  /* =========================================================
     PREVIOUS
  ========================================================= */

  const prev = () => {
    if (parsedSliders.length <= 1) return;

    setCurrentIndex((current) =>
      current === 0
        ? parsedSliders.length - 1
        : current - 1
    );
  };

  /* =========================================================
     AUTOPLAY
     5 SECONDS
  ========================================================= */

  useEffect(() => {
    if (parsedSliders.length <= 1) return;

    if (isHovered) return;

    const interval = setInterval(() => {
      setCurrentIndex((current) =>
        current === parsedSliders.length - 1
          ? 0
          : current + 1
      );
    }, 5000);

    return () => {
      clearInterval(interval);
    };
  }, [parsedSliders.length, isHovered]);

  /* =========================================================
     RESET INDEX WHEN DATA CHANGES
  ========================================================= */

  useEffect(() => {
    if (
      parsedSliders.length > 0 &&
      currentIndex >= parsedSliders.length
    ) {
      setCurrentIndex(0);
    }
  }, [parsedSliders.length, currentIndex]);

  /* =========================================================
     SWIPE
  ========================================================= */

  const minSwipeDistance = 50;

  const onTouchStart = (e: React.TouchEvent) => {
    setTouchEnd(null);

    setTouchStart(
      e.targetTouches[0].clientX
    );
  };

  const onTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(
      e.targetTouches[0].clientX
    );
  };

  const onTouchEnd = () => {
    if (
      touchStart === null ||
      touchEnd === null
    ) {
      return;
    }

    const distance = touchStart - touchEnd;

    const isLeftSwipe =
      distance > minSwipeDistance;

    const isRightSwipe =
      distance < -minSwipeDistance;

    if (isLeftSwipe) {
      next();
    }

    if (isRightSwipe) {
      prev();
    }

    setTouchStart(null);
    setTouchEnd(null);
  };

  /* =========================================================
     RENDER
  ========================================================= */

  return (
    <div
      className="relative w-full overflow-hidden"
      aria-roledescription="carousel"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div
        className="max-w-[1300px] mx-auto w-full relative flex flex-col md:flex-col items-center md:items-center justify-center md:justify-between gap-6 md:gap-5 px-2 md:px-12 lg:px-14 xl:px-5 py-8 md:py-0 mt-5 md:mt-13 xl:mt-26 carousel-wrapper"
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
      >
        {/* ==================================================
            CONTENT
        ================================================== */}

        <div
          key={currentIndex}
          className="program-slider-animation flex w-full md:flex-row flex-col items-center"
        >
          {/* ==================================================
              IMAGE
          ================================================== */}

          <div className="w-full sm:max-w-1/2 lg:max-w-[45%] flex items-center justify-center flex-col content-image-left">
            <Image
              src={
                slide.image
                  ? withCDN(slide.image)
                  : "/placeholder.svg"
              }
              alt={`slide-${slide.id}`}
              width={400}
              height={300}
              className="program-main-image object-contain w-[300px] h-[250px] md:w-[350px] md:h-[295px] lg:w-[580px] lg:h-[420px]"
            />

            {slide.title && (
              <h3 className=" program-main-image text-[#0097dc] text-[15px] md:text-[14px] lg:text-[15px] uppercase py-[10px] px-[30px] md:px-[24px] lg:px-[30px] rounded-full bg-white shadow-[6px_6px_14px_#00000040] w-fit mt-[-48px] mb-[50px] lg:mt-[-90px] lg:mb-[100px] lg:mr-[-100px]">
                {slide.title}
              </h3>
            )}
          </div>

          {/* ==================================================
              TEXT
          ================================================== */}

          <div className="content-slider-left lg:max-w-[55%]">
            <div className="w-full mb-0 md:mb-10 text-center md:text-left text-[#0097DC] text-[20px] font-medium lg:text-[20px] xl:text-[20px] 2xl:text-[25px] tracking-[0.02em] xl:min-w-[570px] slide-description-txt lg:pl-[30px]">
              {!isProgramInnerPage && (
                <div className="flex items-center justify-center gap-[10px] md:gap-[30px] mb-[30px] max-[768px]:justify-center program-age-range">
                  <div className="w-[150px] h-[100px] shadow-[4px_4px_10px_#00000040] rounded-[33px]">
                    <Image
                      src={
                        slide.logoImage ||
                        "/placeholder.svg"
                      }
                      alt={`slide-${slide.id}`}
                      width={150}
                      height={100}
                      className="object-cover w-[150px] h-[100px]"
                    />
                  </div>

                  <div>
                    <h3 className="text-[30px] md:text-[40px] text-[#58585A] font-bold">
                      {slide.age}
                    </h3>

                    <p className="text-[16px] text-[#58585A] font-light uppercase max-[768px]:w-[100px]">
                      years old program
                    </p>
                  </div>
                </div>
              )}

              <div className="text-center">
                {slide.text}
              </div>
            </div>
          </div>
        </div>

        {/* ==================================================
            DESKTOP ARROWS
        ================================================== */}

        <div className="flex items-center gap-5 justify-center md:max-w-[50%] lg:max-w-[55%] w-full ml-auto mr-0 md:mt-[-50px] lg:mt-[-100px] md:mb-[50px] xl:mb-[100px]">
          {/* LEFT */}

          <div className="flex">
            <button
              type="button"
              onClick={prev}
              aria-label="Previous slide"
              className="transition-transform duration-300 hover:scale-110 active:scale-95 w-[30px] h-[30px] lg:w-[30px] lg:h-[30px] xl:w-[40px] xl:h-[40px]"
            >
              <Image
                src={withCDN("/arrow-left.svg")}
                alt="Previous"
                width={40}
                height={40}
                className="object-contain cursor-pointer w-[30px] h-[30px] lg:w-[30px] lg:h-[30px] xl:w-[40px] xl:h-[40px]"
              />
            </button>
          </div>

          {/* RIGHT */}

          <div className="flex">
            <button
              type="button"
              onClick={next}
              aria-label="Next slide"
              className="transition-transform duration-300 hover:scale-110 active:scale-95 w-[30px] h-[30px] lg:w-[30px] lg:h-[30px] xl:w-[40px] xl:h-[40px]"
            >
              <Image
                src={withCDN("/arrow-right.svg")}
                alt="Next"
                width={40}
                height={40}
                className="object-contain cursor-pointer w-[30px] h-[30px] lg:w-[30px] lg:h-[30px] xl:w-[40px] xl:h-[40px]"
              />
            </button>
          </div>
        </div>
      </div>

      {/* =====================================================
          MOBILE ARROWS
      ===================================================== */}

      <div className="hidden">
        {/* LEFT */}

        <div className="absolute top-[180px] sm:top-1/3 left-6 -translate-y-1/2 z-10">
          <button
            type="button"
            onClick={prev}
            aria-label="Previous slide"
            className="transition-transform duration-300 active:scale-90"
          >
            <Image
              src={withCDN("/arrow-left.svg")}
              alt="Previous"
              width={32}
              height={32}
              className="object-contain cursor-pointer"
            />
          </button>
        </div>

        {/* RIGHT */}

        <div className="absolute top-[180px] sm:top-1/3 right-4 -translate-y-1/2 z-10">
          <button
            type="button"
            onClick={next}
            aria-label="Next slide"
            className="transition-transform duration-300 active:scale-90"
          >
            <Image
              src={withCDN("/arrow-right.svg")}
              alt="Next"
              width={32}
              height={32}
              className="object-contain cursor-pointer"
            />
          </button>
        </div>
      </div>
    </div>
  );
}
