"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";
import AnimatedScroll from "../../ui/Animated-Scroll/AnimatedScroll";
import { SliderItem } from "@/src/lib/types/home";
import { withCDN, optimizedImage } from "@/src/lib/utils";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";
import ImageLightbox from "../../ui/ImageLightbox";

type SlideDirection = "next" | "prev";

export default function ClientDiscoverSlider({
  data,
  mainHeading,
  ctaText,
  sliderTexts,
}: {
  data: SliderItem[];
  mainHeading: string;
  ctaText: string;
  sliderTexts?: string[];
}) {
  /* STATE */
  const [activeTab, setActiveTab] = useState(0);
  const [activeImage, setActiveImage] = useState(
    data[0]?.mainImage || ""
  );
  const [activeImageIndex, setActiveImageIndex] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  const [mobileSlideDirection, setMobileSlideDirection] =
    useState<SlideDirection>("next");

  /* CURRENT DATA */
  const currentData = data[activeTab] ?? data[0];

  /* REFS */
  const tabContainerRef = useRef<HTMLDivElement | null>(null);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const touchStartX = useRef<number | null>(null);
  const touchStartY = useRef<number | null>(null);
  const desktopPointerStartX = useRef<number | null>(null);

  /* GALLERY IMAGES */
  const galleryImages = useMemo(
    () =>
      Array.from(
        new Set(
          [
            currentData?.mainImage,
            ...(currentData?.thumbnails || []),
          ].filter(Boolean) as string[]
        )
      ),
    [currentData]
  );

  /* MOBILE IMAGES */
  const mobileImages = galleryImages;

  /* MOBILE SLIDE ANIMATION */
  const mobileSlideVariants = {
    enter: (direction: SlideDirection) => ({
      x: direction === "next" ? "100%" : "-100%",
      scale: 0.88,
      opacity: 1,
    }),

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

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

  const slideTransition = {
    x: {
      duration: 0.5,
      ease: [0.22, 1, 0.36, 1] as [
        number,
        number,
        number,
        number
      ],
    },
    scale: {
      duration: 0.5,
      ease: [0.22, 1, 0.36, 1] as [
        number,
        number,
        number,
        number
      ],
    },
    opacity: {
      duration: 0.3,
    },
  };

  /* SCROLL ACTIVE TAB INTO VIEW ON MOBILE */
  const scrollToTab = (index: number) => {
    if (typeof window === "undefined" || window.innerWidth >= 768) {
      return;
    }

    const container = tabContainerRef.current;
    const tab = tabRefs.current[index];

    if (!container || !tab) return;

    const maxScroll = Math.max(
      0,
      container.scrollWidth - container.clientWidth
    );

    // First tab: return to the beginning.
    if (index === 0) {
      container.scrollTo({
        left: 0,
        behavior: "smooth",
      });
      return;
    }

    // Last tab: scroll to the actual end of the tab strip.
    if (index === data.length - 1) {
      container.scrollTo({
        left: maxScroll,
        behavior: "smooth",
      });
      return;
    }

    // Center other active tabs without exceeding scroll bounds.
    const containerRect = container.getBoundingClientRect();
    const tabRect = tab.getBoundingClientRect();

    const offset =
      tabRect.left -
      containerRect.left -
      container.clientWidth / 2 +
      tab.clientWidth / 2;

    const targetScroll = Math.max(
      0,
      Math.min(maxScroll, container.scrollLeft + offset)
    );

    container.scrollTo({
      left: targetScroll,
      behavior: "smooth",
    });
  };

  /* UPDATE IMAGE WHEN ACTIVE TAB CHANGES */
  useEffect(() => {
    const firstImage = mobileImages[0] || "";

    setMobileSlideDirection("next");
    setActiveImageIndex(0);
    setActiveImage(firstImage);
  }, [activeTab, mobileImages]);

  /* OPEN LIGHTBOX */
  const openLightbox = () => {
    const index = galleryImages.indexOf(activeImage);
    setLightboxIndex(index >= 0 ? index : 0);
  };

  /* CENTRALIZED IMAGE NAVIGATION */
  const navigateToImage = (
    index: number,
    direction: SlideDirection
  ) => {
    if (!mobileImages.length) return;

    const safeIndex =
      ((index % mobileImages.length) + mobileImages.length) %
      mobileImages.length;

    if (safeIndex === activeImageIndex) return;

    setMobileSlideDirection(direction);
    setActiveImageIndex(safeIndex);
    setActiveImage(mobileImages[safeIndex]);
  };

  /* PREVIOUS IMAGE: ALWAYS MOVE RIGHT */
  const handlePrevImage = () => {
    if (mobileImages.length <= 1) return;

    const previousIndex =
      activeImageIndex === 0
        ? mobileImages.length - 1
        : activeImageIndex - 1;

    navigateToImage(previousIndex, "prev");
  };

  /* NEXT IMAGE: ALWAYS MOVE LEFT */
  const handleNextImage = () => {
    if (mobileImages.length <= 1) return;

    const nextIndex =
      activeImageIndex === mobileImages.length - 1
        ? 0
        : activeImageIndex + 1;

    navigateToImage(nextIndex, "next");
  };

  /* IMAGE DOT CLICK */
  const handleImageDotClick = (index: number) => {
    if (index === activeImageIndex) return;

    let direction: SlideDirection;

    if (
      activeImageIndex === mobileImages.length - 1 &&
      index === 0
    ) {
      direction = "next";
    } else if (
      activeImageIndex === 0 &&
      index === mobileImages.length - 1
    ) {
      direction = "prev";
    } else {
      direction = index > activeImageIndex ? "next" : "prev";
    }

    navigateToImage(index, direction);
  };

  /* PREVIOUS TAB */
  const handlePrevTab = () => {
    if (!data.length) return;

    const next = activeTab === 0 ? data.length - 1 : activeTab - 1;

    setActiveTab(next);
    scrollToTab(next);
  };

  /* NEXT TAB */
  const handleNextTab = () => {
    if (!data.length) return;

    const next = activeTab === data.length - 1 ? 0 : activeTab + 1;

    setActiveTab(next);
    scrollToTab(next);
  };

  /* MOBILE IMAGE SWIPE START */
  const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
    const touch = e.touches[0];

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

  /* MOBILE IMAGE SWIPE END */
  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;

    if (Math.abs(deltaY) > Math.abs(deltaX)) return;
    if (Math.abs(deltaX) < 50) return;

    if (deltaX < 0) {
      handleNextImage();
    } else {
      handlePrevImage();
    }
  };

  /* MOBILE CONTENT SWIPE: CHANGE TAB */
  const handleContentTouchStart = (
    e: React.TouchEvent<HTMLDivElement>
  ) => {
    if (window.innerWidth >= 768) return;
    if ((e.target as HTMLElement).closest("button, a")) return;

    const touch = e.touches[0];

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

  const handleContentTouchEnd = (
    e: React.TouchEvent<HTMLDivElement>
  ) => {
    if (window.innerWidth >= 768) return;

    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;

    if (Math.abs(deltaY) > Math.abs(deltaX)) return;
    if (Math.abs(deltaX) < 50) return;

    if (deltaX < 0) {
      handleNextTab();
    } else {
      handlePrevTab();
    }
  };

  /* DESKTOP MOUSE DRAG: CHANGE TAB */
  const handleDesktopPointerDown = (
    e: React.PointerEvent<HTMLDivElement>
  ) => {
    if (
      window.innerWidth < 768 ||
      e.pointerType !== "mouse" ||
      e.button !== 0
    ) {
      return;
    }

    if ((e.target as HTMLElement).closest("button, a, img")) return;

    desktopPointerStartX.current = e.clientX;
    e.currentTarget.setPointerCapture(e.pointerId);
  };

  const handleDesktopPointerUp = (
    e: React.PointerEvent<HTMLDivElement>
  ) => {
    if (desktopPointerStartX.current === null) return;

    const deltaX = desktopPointerStartX.current - e.clientX;
    desktopPointerStartX.current = null;

    if (e.currentTarget.hasPointerCapture(e.pointerId)) {
      e.currentTarget.releasePointerCapture(e.pointerId);
    }

    if (Math.abs(deltaX) < 50) return;

    if (deltaX > 0) {
      handleNextTab();
    } else {
      handlePrevTab();
    }
  };

  const handleDesktopPointerCancel = (
    e: React.PointerEvent<HTMLDivElement>
  ) => {
    desktopPointerStartX.current = null;

    if (e.currentTarget.hasPointerCapture(e.pointerId)) {
      e.currentTarget.releasePointerCapture(e.pointerId);
    }
  };

  return (
    <section
      className="px-4 md:px-10 lg:px-16 xl:px-12 relative w-full py-16 md:py-20 overflow-hidden
        xl:mt-[-6px] 2xl:mt-10 md:mt-[10px] lg:mt-[-30px] mt-[-30px]
        bg-transparent pt-30 xl:pt-15 max-[767px]:pt-8 Descover-container"
    >
      {/* BACKGROUND */}
      <div className="absolute inset-0 w-full h-full -z-10">
        <div
          className="block md:hidden w-full h-full max-[767px]:mt-[-20px] dis-bg-img"
          style={{
            backgroundImage: `url('${optimizedImage(
              "https://yefranchisees.b-cdn.net/frontend/home/path.png",
              828
            )}')`,
            backgroundSize: "cover",
            backgroundRepeat: "repeat",
            backgroundPosition: "top",
          }}
        />

        <div
          className="hidden md:block w-full h-full"
          style={{
            backgroundImage: `url('${optimizedImage(
              "https://yefranchisees.b-cdn.net/frontend/discover/bg%20(14).png",
              1920
            )}')`,
            backgroundSize: "cover",
            backgroundRepeat: "repeat",
            backgroundPosition: "start",
          }}
        />
      </div>

      {/* MAIN CONTENT */}
      <div className="w-full max-w-[1300px] mx-auto md:pt-8 lg:pt-0 xl:pb-5">
        {/* HEADING */}
        <h1
          className="text-[30px] 2xl:text-[50px] md:text-[30px] lg:text-[50px] xl:text-[50px] px-1 lg:px-2 xl:px-0
            font-[700] text-[#0097DC] uppercase text-balance mb-2 md:mb-2 leading-tight discover-title"
          dangerouslySetInnerHTML={{ __html: mainHeading }}
        />

        {/* TABS */}
        <div
          ref={tabContainerRef}
          className="flex flex-nowrap w-full gap-2 overflow-x-auto md:overflow-x-hidden no-scrollbar md:gap-3
            items-stretch pb-5"
          style={{
            WebkitOverflowScrolling: "touch",
            overscrollBehaviorX: "contain",
          }}
        >
          {data.map((item, index) => (
            <div
              key={item.id || index}
              className="flex w-auto flex-none md:w-auto md:flex-1 md:min-w-0 items-stretch discover-tab-btn"
            >
              <button
                ref={(el) => {
                  tabRefs.current[index] = el;
                }}
                type="button"
                onClick={() => {
                  setActiveTab(index);
                  scrollToTab(index);
                }}
                className={`text-[16px] sm:text-[16px] md:text-[14px] lg:text-[16px] xl:text-[16px] 2xl:text-[16px]
                  transition py-2 leading-tight w-24 md:w-full h-full flex items-center justify-center break-words whitespace-normal
                  px-1 md:px-2 lg:px-2 xl:px-1 cursor-pointer text-center
                  border-[#0097DC] rounded-[7px] px-[9px] md:px-[6px] lg:px-[10px] py-[10px] bg-[#fff]
                  ${
                    activeTab === index
                      ? "text-[#0097DC] border-[2px]"
                      : "text-gray-800 hover:text-gray-900 border"
                  }`}
              >
                <span>{item.tabTitle}</span>
              </button>
            </div>
          ))}
        </div>

        {/* CONTENT */}
        <div
          onMouseEnter={() => setIsPaused(true)}
          onMouseLeave={() => setIsPaused(false)}
          onPointerDown={handleDesktopPointerDown}
          onPointerUp={handleDesktopPointerUp}
          onPointerCancel={handleDesktopPointerCancel}
          className="relative select-none flex flex-col-reverse md:justify-between md:flex-row gap-1
            lg:gap-9 items-center md:items-start pb-8 md:pb-0 lg:pb-12 px-1 md:px-0"
        >
          {/* LEFT CONTENT */}
          <div
            onTouchStart={handleContentTouchStart}
            onTouchEnd={handleContentTouchEnd}
            className="w-full md:w-[50%] md:h-[222px] lg:w-[342px] lg:min-h-[309px] lg:max-h-[309px]
              xl:w-[470px] xl:min-h-[309px] xl:max-h-[309px] 2xl:w-[470px] 2xl:min-h-[309px]
              2xl:max-h-[309px] flex flex-col gap-6 mt-4 lg:mt-2 xl:mt-2 md:mt-[-24px]
              lg:flex-shrink-0 discover-card-left touch-pan-y"
          >
            <div>
              <h2
                className="text-[18px] md:text-[20px] lg:text-[26px] xl:text-[30px] 2xl:text-[30px] font-medium
                  text-[#0097DC] uppercase mb-2 leading-tight pt-2 xl:pt-3 pr-0"
              >
                {currentData?.contentTitle}
              </h2>

              <p
                className="text-[18px] md:text-[16px] lg:text-[20px] xl:text-[22px] 2xl:text-[22px] text-[#58585A]
                  leading-normal md:leading-tight xl:leading-[32px] font-light discover-text-left"
              >
                {currentData?.description}
              </p>
            </div>

            {/* CTA */}
            <LanguageAwareLink
              href="/programs"
              className="inline-flex gap-2 items-center justify-center bg-[#0097DC] hover:shadow-[10px_14px_14px_#0000000D]
                active:bg-[#0084C1] text-white font-regular tracking-[0.5px] px-7 py-2 rounded-full transition
                w-fit max-[480px]:w-full"
            >
              <Image
                src={withCDN("/gear-white.png")}
                alt="Ticket Icon"
                width={20}
                height={20}
                className="w-5 h-5 object-contain"
                loading="lazy"
              />
              <span className="text-[18px] md:text-[14px] lg:text-[16px] xl:text-[24px] 2xl:text-[24px] font-regular cursor-pointer max-[360px]:text-[14px]">
                {ctaText}
              </span>
            </LanguageAwareLink>
          </div>

          {/* RIGHT IMAGE SECTION */}
          <div
            className="relative sm:items-stretch w-[85%] md:w-[50%] lg:w-[60%] flex gap-4 lg:gap-6 px-0
              h-[220px] md:h-[320px] lg:h-[350px] xl:h-[400px] 2xl:h-[424px] overflow-visible mb-[24px]
              md:mb-0 touch-pan-y"
          >
            <div className="flex w-full h-full gap-4 items-start md:flex-col lg:flex-row">
              {/* MAIN IMAGE */}
              <div
                className="flex-1 h-full min-h-[180px] md:min-h-[240px] lg:min-h-[410px] xl:min-h-[445px] 2xl:min-h-[470px]
                  rounded-[16px] lg:rounded-[32px] overflow-hidden imgss touch-pan-y"
                onTouchStart={handleTouchStart}
                onTouchEnd={handleTouchEnd}
              >
                <div className="w-full h-full rounded-2xl overflow-hidden relative">
                  {/* MOBILE ANIMATED IMAGE */}
                  <AnimatePresence
                    initial={false}
                    custom={mobileSlideDirection}
                    mode="sync"
                  >
                    <motion.img
                      key={activeImageIndex}
                      src={activeImage}
                      alt="Main"
                      custom={mobileSlideDirection}
                      variants={mobileSlideVariants}
                      initial="enter"
                      animate="center"
                      exit="exit"
                      transition={slideTransition}
                      draggable={false}
                      className="absolute inset-0 w-full h-full object-cover cursor-pointer rounded-2xl md:hidden"
                      loading="lazy"
                      onClick={openLightbox}
                    />
                  </AnimatePresence>

                  {/* DESKTOP IMAGE - UNCHANGED */}
                  <img
                    key={activeImage}
                    src={optimizedImage(activeImage, 1920)}
                    alt="Main"
                    className="hidden md:block w-full h-full object-cover cursor-pointer rounded-2xl discover-mobile-slide-animation"
                    loading="lazy"
                    onClick={openLightbox}
                  />
                </div>
              </div>

              {/* DESKTOP THUMBNAILS */}
              <div
                className="hidden md:flex w-full lg:w-24 xl:w-[130px] flex lg:flex-col gap-3 overflow-x-auto md:overflow-hidden
                  items-center md:items-stretch h-full lg:min-h-[410px] xl:min-h-[445px] 2xl:min-h-[470px]"
              >
                {currentData?.thumbnails?.map((thumbnail, index) => {
                  const isSelected = thumbnail === activeImage;

                  return (
                    <button
                      key={index}
                      type="button"
                      onClick={() => {
                        const imageIndex = mobileImages.indexOf(thumbnail);

                        setActiveImage(thumbnail);

                        if (imageIndex !== -1) {
                          setActiveImageIndex(imageIndex);
                        }
                      }}
                      className="flex-none md:flex-1 rounded-xl overflow-hidden relative cursor-pointer w-[110px] md:w-auto h-[70px] md:h-auto"
                    >
                      <img
                        src={optimizedImage(thumbnail, 256)}
                        alt={`Thumb ${index + 1}`}
                        className={`w-full h-full object-cover transition-all duration-300 ${
                          isSelected ? "brightness-50" : "brightness-100"
                        }`}
                        loading="lazy"
                      />

                      {isSelected && (
                        <div className="absolute inset-0 bg-black/10 pointer-events-none" />
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* MOBILE IMAGE DOTS */}
            <div className="flex md:hidden items-center justify-center gap-4 absolute bottom-[-25px] left-0 w-full z-20">
              <div className="flex items-center justify-center gap-2">
                {mobileImages.map((_, index) => (
                  <button
                    key={index}
                    type="button"
                    onClick={() => handleImageDotClick(index)}
                    aria-label={`Go to image ${index + 1}`}
                    aria-current={
                      activeImageIndex === index ? "true" : undefined
                    }
                    className={`rounded-full transition-all duration-300 ${
                      activeImageIndex === index
                        ? "w-3 h-3 bg-[#0097DC] scale-110"
                        : "w-2.5 h-2.5 bg-gray-300"
                    }`}
                  />
                ))}
              </div>
            </div>

            {/* MOBILE ARROWS */}
            <div className="flex md:hidden items-center justify-between w-full absolute top-[45%] z-20">
              <button
                type="button"
                onClick={handlePrevImage}
                disabled={mobileImages.length <= 1}
                aria-label="Previous image"
                className={`flex items-center justify-center w-8 h-8 ml-[-40px] ${
                  mobileImages.length <= 1
                    ? "opacity-40"
                    : "cursor-pointer"
                }`}
              >
                <Image
                  src={withCDN("/arrow-left.svg")}
                  alt="Previous"
                  width={28}
                  height={28}
                  unoptimized
                />
              </button>

              <button
                type="button"
                onClick={handleNextImage}
                disabled={mobileImages.length <= 1}
                aria-label="Next image"
                className={`flex items-center justify-center w-8 h-8 mr-[-40px] ${
                  mobileImages.length <= 1
                    ? "opacity-40"
                    : "cursor-pointer"
                }`}
              >
                <Image
                  src={withCDN("/arrow-right.svg")}
                  alt="Next"
                  width={28}
                  height={28}
                  unoptimized
                />
              </button>
            </div>
          </div>

          {/* DESKTOP TAB NAVIGATION */}
          <div
            className="flex items-center justify-center md:justify-start gap-3 absolute w-full md:w-[550px] lg:w-[550px]
              bottom-[0%] md:left-10 lg:ml-[-40px] discover-navigaton max-[767px]:hidden"
          >
            <button
              type="button"
              onClick={handlePrevTab}
              className={`flex items-center justify-center w-8 h-8 transition ${
                activeTab === 0
                  ? "opacity-100 cursor-not-allowed"
                  : "cursor-pointer"
              }`}
              aria-label="Previous tab"
            >
              <Image
                src={withCDN("/arrow-left.svg")}
                alt="Previous"
                width={28}
                height={28}
                unoptimized
              />
            </button>

            <button
              type="button"
              onClick={handleNextTab}
              className={`flex justify-center w-8 h-8 transition ${
                activeTab === data.length - 1
                  ? "opacity-100 cursor-not-allowed"
                  : "cursor-pointer"
              }`}
              aria-label="Next tab"
            >
              <Image
                src={withCDN("/arrow-right.svg")}
                alt="Next"
                width={28}
                height={28}
                unoptimized
              />
            </button>
          </div>
        </div>
      </div>

      {/* ANIMATED SCROLL */}
      <div className="absolute bottom-0 left-0 w-full">
        <AnimatedScroll items={sliderTexts} />
      </div>

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