"use client";
import { useState, useRef } from "react";
import "./css/slide.css";
import {IMAGE_BASE} from "@/constants"

export default function Slide({ pack, cards, set_is_last }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [removedIndices, setRemovedIndices] = useState([]);

  const imgRefs = useRef({});
  const startPos = useRef(null);
  const isAnimating = useRef(false);

  const handleStart = (e, index) => {
    if (
      isAnimating.current ||
      index !== currentIndex ||
      removedIndices.includes(index)
    ) {
      return;
    }

    e.preventDefault();

    const clientX = e.type === "touchstart" ? e.touches[0].clientX : e.clientX;
    const clientY = e.type === "touchstart" ? e.touches[0].clientY : e.clientY;

    startPos.current = { x: clientX, y: clientY };
    setIsDragging(true);

    const handleMove = (moveEvent) => {
      if (startPos.current && !isAnimating.current) {
        const moveClientX =
          moveEvent.type === "touchmove"
            ? moveEvent.touches[0].clientX
            : moveEvent.clientX;
        const moveClientY =
          moveEvent.type === "touchmove"
            ? moveEvent.touches[0].clientY
            : moveEvent.clientY;

        const dx = moveClientX - startPos.current.x;
        const dy = moveClientY - startPos.current.y;
        setDragOffset({ x: dx, y: dy });
      }
    };

    const handleEnd = (upEvent) => {
      if (!startPos.current) return;

      const endClientX =
        upEvent.type === "touchend"
          ? upEvent.changedTouches[0].clientX
          : upEvent.clientX;
      const endClientY =
        upEvent.type === "touchend"
          ? upEvent.changedTouches[0].clientY
          : upEvent.clientY;

      const dx = endClientX - startPos.current.x;
      const dy = endClientY - startPos.current.y;

      const threshold = 10;

      if (Math.abs(dx) > threshold || Math.abs(dy) > threshold) {
        let dir;
        if (Math.abs(dx) > Math.abs(dy)) {
          dir = dx > 0 ? "right" : "left";
        } else {
          dir = dy > 0 ? "down" : "up";
        }
        triggerAnimation(index, dir, { x: dx, y: dy });
      } else {
        setDragOffset({ x: 0, y: 0 });
        setIsDragging(false);
      }

      startPos.current = null;
      window.removeEventListener("mousemove", handleMove);
      window.removeEventListener("mouseup", handleEnd);
      window.removeEventListener("touchmove", handleMove);
      window.removeEventListener("touchend", handleEnd);
    };

    window.addEventListener("mousemove", handleMove);
    window.addEventListener("mouseup", handleEnd);
    window.addEventListener("touchmove", handleMove, { passive: false });
    window.addEventListener("touchend", handleEnd);
  };

  const triggerAnimation = (index, direction, currentOffset) => {
    if (isAnimating.current) return;

    const imgEl = imgRefs.current[index];
    if (!imgEl) return;

    isAnimating.current = true;
    setIsDragging(false);

    let finalX, finalY;

    switch (direction) {
      case "up":
        finalX = currentOffset.x;
        finalY = -window.innerHeight;
        break;
      case "down":
        finalX = currentOffset.x;
        finalY = window.innerHeight;
        break;
      case "left":
        finalX = -window.innerWidth;
        finalY = currentOffset.y;
        break;
      case "right":
        finalX = window.innerWidth;
        finalY = currentOffset.y;
        break;
    }

    // Start animation immediately from current drag position
    imgEl.style.transition = "transform 0.3s ease-out, opacity 0.3s ease-out";
    imgEl.style.transform = `translate(calc(-50% + ${finalX}px), calc(-50% + ${finalY}px))`;
    imgEl.style.opacity = "0";

    // Mark as removed immediately to prevent rendering
    setTimeout(() => {
      setRemovedIndices((prev) => {
        if (prev.includes(index)) return prev;
        return [...prev, index];
      });

      const nextIndex = index + 1;
      setCurrentIndex(nextIndex);
      setDragOffset({ x: 0, y: 0 });
      isAnimating.current = false;

      if (nextIndex >= cards.length) {
        set_is_last(true);
      }
    }, 300);
  };

  return (
    <div className="slide cards">
      <div className="in">
        {cards.map((c, index) => {
          if (removedIndices.includes(index)) {
            return null;
          }

          if (index < currentIndex) {
            return null;
          }

          const isCurrentCard = index === currentIndex;

          const inlineStyle = {
            cursor: isCurrentCard
              ? isDragging
                ? "grabbing"
                : "grab"
              : "default",
            userSelect: "none",
            zIndex:
              cards.length - index + (isCurrentCard && isDragging ? 9999 : 0),
            pointerEvents: isCurrentCard ? "auto" : "none",
            opacity: isCurrentCard ? 1 : 1,
            willChange: isCurrentCard ? "transform" : "auto",
          };

          if (isCurrentCard && isDragging) {
            inlineStyle.transform = `translate(calc(-50% + ${dragOffset.x}px), calc(-50% + ${dragOffset.y}px))`;
            inlineStyle.transition = "none";
          } else if (!isCurrentCard) {
            inlineStyle.transform = "translate(-50%, -50%)";
            inlineStyle.transition = "none";
          } else {
            inlineStyle.transform = "translate(-50%, -50%)";
          }

          return (
            <img
              key={`card-${index}`}
              ref={(el) => {
                if (el) imgRefs.current[index] = el;
              }}
              src={`${IMAGE_BASE}/${c.cover_image.replace(/^\/+/, "")}`}
              style={inlineStyle}
              draggable={false}
              onMouseDown={(e) => handleStart(e, index)}
              onTouchStart={(e) => handleStart(e, index)}
              className={
                c.probability === "Reverse Holofoil"
                  ? "object-contain card-image-wrapper rounded-[10px] !w-fit -mt-10"
                  : "object-contain rounded-[10px] !w-fit -mt-10"
              }
              alt={`Card ${index}`}
            />
          );
        })}
      </div>
    </div>
  );
}
