import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import styles from "../css/SlidingGallery.module.css";

const SlidingGallery = ({
  views = [],
  className = "",
  showPagination = true,
  autoScroll = false,
  autoScrollInterval = 5000,
  onSlideChange = () => {},
  height = "100vh",
}) => {
  const [activeIdx, setActiveIdx] = useState(0);
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const scrollRef = useRef(null);
  const galleryRef = useRef(null);
  const autoScrollRef = useRef(null);

  // Auto-scroll functionality
  useEffect(() => {
    if (autoScroll && views.length > 1) {
      autoScrollRef.current = setInterval(() => {
        setActiveIdx((prevIdx) => {
          const nextIdx = (prevIdx + 1) % views.length;
          goToSlide(nextIdx);
          return nextIdx;
        });
      }, autoScrollInterval);

      return () => {
        if (autoScrollRef.current) {
          clearInterval(autoScrollRef.current);
        }
      };
    }
  }, [autoScroll, autoScrollInterval, views.length]);

  // Clear auto-scroll on user interaction
  const handleUserInteraction = () => {
    if (autoScrollRef.current) {
      clearInterval(autoScrollRef.current);
    }
  };

  useEffect(() => {
    const updateDimensions = () => {
      if (galleryRef.current) {
        setDimensions({
          width: galleryRef.current.clientWidth,
          height: galleryRef.current.clientHeight,
        });
      }
    };

    // Initial dimension update
    updateDimensions();

    // Add resize listener
    window.addEventListener("resize", updateDimensions);

    // Cleanup
    return () => window.removeEventListener("resize", updateDimensions);
  }, []);

  useEffect(() => {
    // Recalculate active index when dimensions change
    if (scrollRef.current && dimensions.width > 0) {
      const scrollLeft = scrollRef.current.scrollLeft;
      const slideWidth = dimensions.width;
      const index = Math.round(scrollLeft / slideWidth);
      setActiveIdx(index);
    }
  }, [dimensions]);

  const handleScroll = (event) => {
    handleUserInteraction();
    const scrollLeft = event.target.scrollLeft;
    const slideWidth = dimensions.width;
    const index = Math.round(scrollLeft / slideWidth);
    if (index !== activeIdx) {
      setActiveIdx(index);
      onSlideChange(index);
    }
  };

  const goToSlide = (index) => {
    if (scrollRef.current) {
      scrollRef.current.scrollTo({
        left: index * dimensions.width,
        behavior: "smooth",
      });
    }
  };

  const handleDotClick = (index) => {
    handleUserInteraction();
    goToSlide(index);
    setActiveIdx(index);
    onSlideChange(index);
  };

  // Early return if no views
  if (!views || views.length === 0) {
    return (
      <div className={`${styles.gallery} ${className}`}>
        <div className={styles.emptyState}>
          <p>No content to display</p>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`${styles.gallery} ${className}`}
      ref={galleryRef}
      style={{ height }}
    >
      <div
        className={styles.scrollContainer}
        ref={scrollRef}
        onScroll={handleScroll}
        style={{
          width: "100%",
          height: "100%",
        }}
      >
        {views.map((item) => (
          <div
            key={item.id}
            className={styles.slide}
            style={{
              width: dimensions.width,
              height: "100%",
              flexShrink: 0,
            }}
          >
            {item.content}
          </div>
        ))}
      </div>
      {showPagination && views.length > 1 && (
        <div className={styles.pagination}>
          {views.map((_, index) => (
            <div
              key={index}
              className={`${styles.dot} ${
                activeIdx === index ? styles.activeDot : styles.inactiveDot
              }`}
              onClick={() => handleDotClick(index)}
              style={{ cursor: "pointer" }}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default SlidingGallery;
