import { useState, useEffect } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Thumbs, Pagination, Navigation, Mousewheel, FreeMode } from "swiper/modules";
import { Skeleton } from "antd";

import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/thumbs";
import "swiper/css/navigation";
import styles from "./Banner.module.scss";
import storiesStyles from "./Stories.module.scss";

import { useGetCarouselsQuery, useGetStoriesQuery } from "../../app/api/bannersApi.js";
import StoryViewer from "../StoryViewer/StoryViewer";
import { useDragScroll } from "./hook/useDragScroll.js";

function Carousel() {
  const { data: carouselData, isLoading, isError } = useGetCarouselsQuery();
  const { data: storiesData, isLoading: isStoriesLoading, isError: isStoriesError } = useGetStoriesQuery();

  const [thumbsSwiper, setThumbsSwiper] = useState(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [isAnimating, setIsAnimating] = useState(true);
  const [selectedStoryIndex, setSelectedStoryIndex] = useState(null);
  const [viewedStoryIds, setViewedStoryIds] = useState(new Set());

  const storiesScrollRef = useDragScroll();

  useEffect(() => {
    setIsAnimating(false);
    const timer = setTimeout(() => setIsAnimating(true), 50);
    return () => clearTimeout(timer);
  }, [activeIndex]);

  const handleSlideChange = (swiper) => {
    setActiveIndex(swiper.realIndex);
  };

  const handleImageClick = (link) => {
    if (link) window.open(link, "_blank", "noopener,noreferrer");
  };

  const handleStoryViewed = (storyIndex) => {
    const storyId = storiesData?.data[storyIndex]?.id;
    if (storyId) {
      setViewedStoryIds((prev) => new Set(prev).add(storyId));
    }
  };

  const handleStoryClick = (index) => {
    if (storiesScrollRef.current?.dataset.dragged) return;
    setSelectedStoryIndex(index);
  };

  if (isLoading) {
    return (
      <div className={styles.carouselContainer}>
        <div className={styles.mainSliderSkeleton}>
          <Skeleton.Image active className={styles.fullWidthSkeleton} />
        </div>
      </div>
    );
  }

  if (isError || !carouselData?.data?.length) return null;

  return (
    <>
      {!isStoriesLoading && !isStoriesError && storiesData?.data?.length > 0 && (
        <div className={storiesStyles.storiesContainer}>
          <div className={storiesStyles.storiesWrapper} ref={storiesScrollRef}>
            {storiesData.data.map((story, index) => {
              const isViewed = viewedStoryIds.has(story.id);
              return (
                
                <button
                  key={story.id}
                  className={storiesStyles.storyButton}
                  onClick={() => handleStoryClick(index)}
                >
                  <div className={`${storiesStyles.storyAvatar} ${isViewed ? storiesStyles.viewed : ""}`}>
                    <img src={story.thumbnail || story.photo} alt={story.title} />
                  </div>
                  <span className={storiesStyles.storyLabel}>{story.title}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {selectedStoryIndex !== null && (
        <StoryViewer
          stories={storiesData.data}
          initialIndex={selectedStoryIndex}
          onClose={() => setSelectedStoryIndex(null)}
          onStoryViewed={handleStoryViewed}
        />
      )}

      <div className={styles.carouselContainer}>
        <Swiper
          modules={[Thumbs, Pagination, Navigation, Autoplay]}
          thumbs={{ swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null }}
          autoplay={{ delay: 3000, disableOnInteraction: false }}
          loop={true}
          pagination={{ clickable: true }}
          navigation={true}
          className={styles.mainSlider}
          onSlideChange={handleSlideChange}
        >
          {carouselData.data.map((item) => (
            <SwiperSlide key={item.id}>
              <div
                className={styles.imageWrapper}
                onClick={() => handleImageClick(item.link)}
                style={{ cursor: item.link ? "pointer" : "default" }}
              >
                <img src={item.image} alt={item.title || "Banner"} />
              </div>
            </SwiperSlide>
          ))}
        </Swiper>

        <Swiper
          modules={[Thumbs, FreeMode, Mousewheel]}
          onSwiper={setThumbsSwiper}
          slidesPerView={4}
          spaceBetween={10}
          direction="vertical"
          watchSlidesProgress={true}
          className={styles.thumbSlider}
        >
          {carouselData.data.map((item, index) => (
            <SwiperSlide key={item.id}>
              <div className={`${styles.thumbWrapper} ${index === activeIndex ? styles.active : ""}`}>
                <img src={item.thumbnail} alt={`Thumb ${index}`} />
                {index === activeIndex && isAnimating && (
                  <div className={styles.progressContainer}>
                    <div className={styles.progressBarImg}></div>
                    <div className={styles.progressBar}></div>
                  </div>
                )}
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
    </>
  );
}

export default Carousel;