"use client";

import styles from "./Carousel.module.css";
import { useEffect, useRef, useState } from "react";
import Video from "@/components/Video/Video";
import useMediaQuery from "@/hooks/useMediaQuery";

type Item = {
  name?: string;
  image?: string;
  video?: string;
  videoSquare?: string;
  poster?: string;
};

type CarouselProps = {
  items?: Array<Item>;
  startingIndex?: number;
};

const MOBILE_BREAKPOINT = "(max-width: 992px)";

const Carousel = ({ items = [], startingIndex = 0 }: CarouselProps) => {
  const [trackPosition, setTrackPosition] = useState<number>(0);
  const [absoluteIndex, setAbsoluteIndex] = useState<number>(startingIndex);
  const [initialX, setInitialX] = useState<number>(0);
  const [hasMounted, setHasMounted] = useState(false);
  const trackRef = useRef<HTMLDivElement | null>(null);
  const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
  const touchStartRef = useRef<{ x: number; y: number } | null>(null);
  const didSwipeRef = useRef(false);
  const isAnimatingRef = useRef(false);
  const totalItems = items.length;
  const isMobile = useMediaQuery(MOBILE_BREAKPOINT);

  const SWIPE_THRESHOLD = 50;

  const getItemWidth = (): number => trackRef.current?.offsetWidth || 0;

  const getVideoSrc = (item: Item): string | undefined =>
    isMobile ? item.videoSquare ?? item.video : item.video;

  const determineHoverIcon = (index: number) => {
    if (index === getPreviousItem()) {
      return "/image/icon/skip_previous.svg";
    } else if (index === getNextItem()) {
      return "/image/icon/skip_next.svg";
    }
  };

  const handleTransitionStart = () => {
    isAnimatingRef.current = true;
  };

  const handleTransitionEnd = () => {
    isAnimatingRef.current = false;
  };

  const handleKeyboardEvents = (e: KeyboardEvent) => {
    const { key } = e;

    if (isAnimatingRef.current) return;

    if (key === "ArrowLeft") {
      setAbsoluteIndex((index) => index - 1);
    } else if (key === "ArrowRight") {
      setAbsoluteIndex((index) => index + 1);
    }
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    if (!isMobile) return;

    const touch = e.touches[0];
    if (!touch) return;

    touchStartRef.current = { x: touch.clientX, y: touch.clientY };
    didSwipeRef.current = false;
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (!isMobile || !touchStartRef.current) return;

    if (isAnimatingRef.current) {
      touchStartRef.current = null;
      return;
    }

    const touch = e.changedTouches[0];
    if (!touch) return;

    const deltaX = touch.clientX - touchStartRef.current.x;
    const deltaY = touch.clientY - touchStartRef.current.y;
    touchStartRef.current = null;

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

    didSwipeRef.current = true;

    if (deltaX < 0) {
      setAbsoluteIndex((index) => index + 1);
    } else {
      setAbsoluteIndex((index) => index - 1);
    }
  };

  const handleTouchCancel = () => {
    touchStartRef.current = null;
  };

  const handleClick = (clickedIndex: number) => {
    if (didSwipeRef.current) {
      didSwipeRef.current = false;
      return;
    }

    if (clickedIndex === getNextItem()) {
      setAbsoluteIndex((index) => index + 1);
    } else if (clickedIndex === getPreviousItem()) {
      setAbsoluteIndex((index) => index - 1);
    }
  };

  const determineItemClass = (index: number) => {
    switch (index) {
      case getPreviousItem():
        return styles.previous;
      case getNextItem():
        return styles.next;
      case localCurrentIndex():
        return styles.current;
    }

    return null;
  };

  const localCurrentIndex = () =>
    ((absoluteIndex % totalItems) + totalItems) % totalItems;

  const getNextItem = () => (localCurrentIndex() + 1) % totalItems;

  const getPreviousItem = () =>
    (localCurrentIndex() - 1 + totalItems) % totalItems;

  const isAdjacentSlide = (index: number) =>
    index === getPreviousItem() ||
    index === localCurrentIndex() ||
    index === getNextItem();

  const calculateItemTransforms = () => {
    const currentIndex = absoluteIndex;
    const totalWidth = getItemWidth() * totalItems;
    const segment = Math.floor(currentIndex / totalItems);
    const baseX = initialX + segment * totalWidth;
    const currentIndexPosition = baseX + localCurrentIndex() * getItemWidth();
    const itemPadding = isMobile ? "1rem" : "3rem";

    return items.map((_, index) => {
      if (index === getPreviousItem()) {
        return {
          transform: `translate3d(${
            currentIndexPosition - getItemWidth()
          }px, 0px, 0px)`,
          opacity: "0.5",
          padding: itemPadding,
        };
      } else if (index === getNextItem()) {
        return {
          transform: `translate3d(${
            currentIndexPosition + getItemWidth()
          }px, 0px, 0px)`,
          opacity: "0.5",
          padding: itemPadding,
        };
      } else if (index === localCurrentIndex()) {
        return {
          transform: `translate3d(${
            baseX + index * getItemWidth()
          }px, 0px, 0px)`,
          opacity: "1",
          padding: "0",
        };
      } else {
        return {
          transform: `translate3d(${
            baseX + index * getItemWidth()
          }px, 0px, 0px)`,
          opacity: "0.5",
          padding: itemPadding,
        };
      }
    });
  };

  const applyTransforms = () => {
    const transforms = calculateItemTransforms();

    itemRefs.current.forEach((item, index) => {
      if (item) {
        const { transform, opacity, padding } = transforms[index];

        const isAdjacent =
          index === getPreviousItem() ||
          index === localCurrentIndex() ||
          index === getNextItem();

        if (isAdjacent) {
          item.style.transform = transform;
          item.style.opacity = opacity;
          item.style.padding = padding;
        } else {
          item.style.opacity = opacity;
          item.style.padding = padding;

          setTimeout(() => {
            item.style.transform = transform;
          }, 600);
        }
      }
    });
  };

  const updateTrackPosition = (): void => {
    const width = absoluteIndex * getItemWidth();
    const position = initialX - width;

    setTrackPosition(position);
  };

  useEffect(() => {
    setHasMounted(true);
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", handleKeyboardEvents);
    document.addEventListener("transitionstart", handleTransitionStart);
    document.addEventListener("transitionend", handleTransitionEnd);

    const resizeObserver = new ResizeObserver(() => {
      updateTrackPosition();
      applyTransforms();
    });

    if (trackRef.current) resizeObserver.observe(trackRef.current);

    updateTrackPosition();
    applyTransforms();

    return () => {
      document.removeEventListener("keydown", handleKeyboardEvents);
      document.removeEventListener("transitionstart", handleTransitionStart);
      document.removeEventListener("transitionend", handleTransitionEnd);

      resizeObserver.disconnect();
    };
  }, [absoluteIndex, isMobile]);

  if (!items.length) return <></>;

  const currentIndex = localCurrentIndex();

  return (
    <div
      className={styles.carousel}
      data-absolute-index={absoluteIndex}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      onTouchCancel={handleTouchCancel}
    >
      <div
        className={styles.track}
        ref={trackRef}
        style={{
          transform: `translate3d(${trackPosition}px, 0px, 0px)`,
        }}
      >
        {items.map((item, index) => {
          const videoSrc = getVideoSrc(item);
          const showVideo =
            hasMounted && isAdjacentSlide(index) && Boolean(videoSrc);
          const isCurrentSlide = index === currentIndex;

          return (
            <div
              key={index}
              className={[styles.item, determineItemClass(index)]
                .join(" ")
                .trim()}
              onClick={() => handleClick(index)}
              ref={(el) => {
                itemRefs.current[index] = el;
              }}
              style={{ padding: index === startingIndex ? "0" : "3rem" }}
              data-hover-icon={determineHoverIcon(index)}
            >
              {showVideo ? (
                <Video
                  key={videoSrc}
                  src={videoSrc}
                  poster={item.poster}
                  play={isCurrentSlide}
                  preload={
                    isCurrentSlide ? "auto" : isMobile ? "none" : "metadata"
                  }
                  fetchPriority={
                    isCurrentSlide && index === 0 ? "high" : "auto"
                  }
                />
              ) : (
                item.poster && (
                  <img
                    className={styles.poster}
                    src={item.poster}
                    alt=""
                    decoding="async"
                    fetchPriority={
                      isCurrentSlide && index === 0 ? "high" : "auto"
                    }
                  />
                )
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default Carousel;
