import { useState, useRef, useEffect } from "react";
import styles from "./ImageCarousel.module.scss";

const ImageCarousel = ({
  images,
  altText,
  showThumbnails = false,
  isDetailView = false,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [scale, setScale] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

  const touchStartX = useRef(0);
  const touchEndX = useRef(0);
  const carouselRef = useRef(null);
  const modalImageRef = useRef(null);

  const hasMultipleImages = Array.isArray(images) && images.length > 1;

  const currentImage =
    hasMultipleImages && images[currentIndex]
      ? images[currentIndex].images_1200x1200
      : images[0]?.images_1200x1200 || "";

  // Auto-slide functionality
  useEffect(() => {
    if (!hasMultipleImages || isModalOpen) return;

    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev === images.length - 1 ? 0 : prev + 1));
    }, 9000);

    return () => clearInterval(interval);
  }, [hasMultipleImages, images, isModalOpen]);

  // Reset zoom/rotation when modal closes or image changes
  useEffect(() => {
    if (!isModalOpen) {
      setScale(1);
      setRotation(0);
      setPosition({ x: 0, y: 0 });
    }
  }, [isModalOpen, currentIndex]);

  const handlePrev = (e) => {
    if (e) e.stopPropagation();
    if (!hasMultipleImages) return;
    setCurrentIndex((prev) => (prev === 0 ? images.length - 1 : prev - 1));
  };

  const handleNext = (e) => {
    if (e) e.stopPropagation();
    if (!hasMultipleImages) return;
    setCurrentIndex((prev) => (prev === images.length - 1 ? 0 : prev + 1));
  };

  const handleThumbnailClick = (index, e) => {
    if (e) e.stopPropagation();
    setCurrentIndex(index);
  };

  const handleTouchStart = (e) => {
    touchStartX.current = e.touches[0].clientX;
  };

  const handleTouchMove = (e) => {
    touchEndX.current = e.touches[0].clientX;
  };

  const handleTouchEnd = () => {
    if (!hasMultipleImages) return;

    const touchDiff = touchStartX.current - touchEndX.current;

    if (Math.abs(touchDiff) > 50) {
      if (touchDiff > 0) {
        handleNext();
      } else {
        handlePrev();
      }
    }
  };

  useEffect(() => {
    if (carouselRef.current) {
      carouselRef.current.classList.add(styles.transitioning);

      const timer = setTimeout(() => {
        if (carouselRef.current) {
          carouselRef.current.classList.remove(styles.transitioning);
        }
      }, 900);

      return () => clearTimeout(timer);
    }
  }, [currentIndex]);

  // Modal zoom functions
  const handleZoomIn = (e) => {
    e.stopPropagation();
    setScale((prev) => Math.min(prev + 0.5, 5));
  };

  const handleZoomOut = (e) => {
    e.stopPropagation();
    setScale((prev) => Math.max(prev - 0.5, 0.5));
  };

  const handleRotateLeft = (e) => {
    e.stopPropagation();
    setRotation((prev) => prev - 90);
  };

  const handleRotateRight = (e) => {
    e.stopPropagation();
    setRotation((prev) => prev + 90);
  };

  const handleReset = (e) => {
    e.stopPropagation();
    setScale(1);
    setRotation(0);
    setPosition({ x: 0, y: 0 });
  };

  const handleFullscreen = (e) => {
    e.stopPropagation();
    if (modalImageRef.current) {
      if (document.fullscreenElement) {
        document.exitFullscreen();
      } else {
        modalImageRef.current.requestFullscreen();
      }
    }
  };

  // Dragging functions
  const handleMouseDown = (e) => {
    if (scale > 1) {
      setIsDragging(true);
      setDragStart({
        x: e.clientX - position.x,
        y: e.clientY - position.y,
      });
    }
  };

  const handleMouseMove = (e) => {
    if (isDragging && scale > 1) {
      setPosition({
        x: e.clientX - dragStart.x,
        y: e.clientY - dragStart.y,
      });
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const openModal = (e) => {
    if (e) e.stopPropagation();
    if (isDetailView) {
      setIsModalOpen(true);
    }
  };

  const closeModal = (e) => {
    if (e) e.stopPropagation();
    setIsModalOpen(false);
  };

  // Keyboard controls
  useEffect(() => {
    if (!isModalOpen) return;

    const handleKeyDown = (e) => {
      switch (e.key) {
        case "Escape":
          closeModal();
          break;
        case "ArrowLeft":
          handlePrev();
          break;
        case "ArrowRight":
          handleNext();
          break;
        case "+":
        case "=":
          handleZoomIn(e);
          break;
        case "-":
          handleZoomOut(e);
          break;
        case "r":
        case "R":
          handleRotateRight(e);
          break;
        default:
          break;
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isModalOpen]);

  if (!hasMultipleImages) {
    return (
      <div className={isDetailView ? styles.fixedFrameContainer : undefined}>
        <img
          src={currentImage || "/placeholder.svg"}
          alt={altText || "Product image"}
          className={`${styles.productImage} ${
            isDetailView ? styles.detailImage : styles.cardImage
          }`}
          onClick={isDetailView ? openModal : undefined}
          style={{ cursor: isDetailView ? "pointer" : "default" }}
        />
        {isDetailView && renderModal()}
      </div>
    );
  }

  function renderModal() {
    if (!isModalOpen) return null;

    return (
      <div className={styles.modalOverlay} onClick={closeModal}>
        <div
          className={styles.modalContent}
          onClick={(e) => e.stopPropagation()}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
        >
          <button className={styles.closeButton} onClick={closeModal}>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              height="24px"
              viewBox="0 -960 960 960"
              width="24px"
              fill="#e3e3e3"
            >
              <path d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z" />
            </svg>
          </button>

          <div className={styles.modalImageContainer} ref={modalImageRef}>
            <img
              src={currentImage || "/placeholder.svg"}
              alt={altText || "Product image"}
              className={styles.modalImage}
              style={{
                transform: `scale(${scale}) rotate(${rotation}deg) translate(${position.x}px, ${position.y}px)`,
                cursor:
                  scale > 1 ? (isDragging ? "grabbing" : "grab") : "default",
              }}
              draggable={false}
            />
          </div>

          {/* Control buttons */}
          <div className={styles.modalControls}>
            <button
              className={styles.controlButton}
              onClick={handlePrev}
              title="Önceki (←)"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <polyline points="15 18 9 12 15 6"></polyline>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleZoomOut}
              title="Uzaklaştır (-)"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="8" y1="11" x2="14" y2="11"></line>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleZoomIn}
              title="Yakınlaştır (+)"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="11" y1="8" x2="11" y2="14"></line>
                <line x1="8" y1="11" x2="14" y2="11"></line>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleFullscreen}
              title="Tam ekran"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleRotateLeft}
              title="Sola döndür"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M2.5 2v6h6M2.66 15.57a10 10 0 1 0 .57-8.38"></path>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleRotateRight}
              title="Sağa döndür (R)"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38"></path>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleReset}
              title="Sıfırla"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"></path>
                <path d="M21 3v5h-5"></path>
                <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"></path>
                <path d="M3 21v-5h5"></path>
              </svg>
            </button>

            <button
              className={styles.controlButton}
              onClick={handleNext}
              title="Sonraki (→)"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <polyline points="9 18 15 12 9 6"></polyline>
              </svg>
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`${styles.carouselWrapper} ${
        isDetailView ? styles.detailCarousel : ""
      }`}
    >
      <div
        className={styles.carouselContainer}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        <div
          ref={carouselRef}
          className={`${styles.imageWrapper} ${
            isDetailView ? styles.fixedFrameContainer : ""
          }`}
          onClick={isDetailView ? openModal : undefined}
          style={{ cursor: isDetailView ? "pointer" : "default" }}
        >
          <img
            src={currentImage || "/placeholder.svg"}
            alt={altText || "Product image"}
            className={`${styles.productImage} ${
              isDetailView ? styles.detailImage : styles.cardImage
            }`}
          />
        </div>

        <button
          onClick={handlePrev}
          className={`${styles.arrowButton} ${styles.leftArrow}`}
          aria-label="Previous image"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="15 18 9 12 15 6"></polyline>
          </svg>
        </button>

        <button
          onClick={handleNext}
          className={`${styles.arrowButton} ${styles.rightArrow}`}
          aria-label="Next image"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="9 18 15 12 9 6"></polyline>
          </svg>
        </button>

        <div className={styles.indicators}>
          {images.map((_, idx) => (
            <span
              key={idx}
              className={`${styles.indicator} ${
                currentIndex === idx ? styles.active : ""
              }`}
              onClick={(e) => handleThumbnailClick(idx, e)}
            />
          ))}
        </div>
      </div>

      {showThumbnails && (
        <div className={styles.thumbnailContainer}>
          {images.map((image, idx) => (
            <div
              key={idx}
              className={`${styles.thumbnail} ${
                currentIndex === idx ? styles.activeThumbnail : ""
              }`}
              onClick={(e) => handleThumbnailClick(idx, e)}
            >
              <img
                src={
                  image.thumbnail || image.images_400x400 || "/placeholder.svg"
                }
                alt={`${altText || "Product"} thumbnail ${idx + 1}`}
              />
            </div>
          ))}
        </div>
      )}

      {isDetailView && renderModal()}
    </div>
  );
};

export default ImageCarousel;
