import { useEffect, useState } from "react";
import FirstSlide from "./slides/FirstSlide";
import SecondSlide from "./slides/SecondSlide";
import ThirdSlide from "./slides/ThirdSlide";
import { SliderContext } from "./Context";
import SwiperPaginationBullets from "../../SwiperPaginationBullets";

const slides = [
  { element: <FirstSlide />, id: 1 },
  { element: <SecondSlide />, id: 2 },
  { element: <ThirdSlide />, id: 3 },
];

const MainPageSlider = () => {
  const [offset, setOffset] = useState(0);
  const [currentSlide, setCurrentSlide] = useState(1);

  useEffect(() => {
    const updatedSlide = -1 * offset + 1;
    setCurrentSlide(updatedSlide);
  }, [offset]);

  const handleRightArrowClick = () => {
    setOffset((currentOffset) => {
      if (currentOffset === -1 * slides.length + 1) {
        return 0;
      }

      return currentOffset - 1;
    });
  };

  const handleLeftArrowClick = () => {
    setOffset((currentOffset) => {
      if (currentOffset === 0) {
        return -1 * slides.length + 1;
      }

      return currentOffset + 1;
    });
  };

  const handleOnSlideChange = (slide: number) => {
    const updatedOffset = (slide - 1) * -1;

    setCurrentSlide(slide);
    setOffset(updatedOffset);
  };

  return (
    <div className="flex flex-col select-none relative">
      <div className="flex h-[calc(100vh-150px)] justify-between w-[calc(100vw-20px)] px-2 pt-20">
        <div className="w-screen overflow-hidden bg-gradient-radial from-[#773272] via-[#1e1530] to-[#1e1530]">
          <div
            className="flex transition-[1.25s] "
            style={{ transform: `translateX(calc(${offset}*100vw))` }}
          >
            <SliderContext.Provider value={currentSlide}>
              {slides.map((slide) => (
                <div key={slide.id}>{slide.element}</div>
              ))}
            </SliderContext.Provider>
          </div>
        </div>

        <div className="">
          <button
            onClick={handleLeftArrowClick}
            className="left-arrow absolute top-[50%] left-4 -translate-y-[50%]"
          ></button>
          <button
            className="right-arrow absolute top-[50%] right-4 -translate-y-[50%]"
            onClick={handleRightArrowClick}
          ></button>
        </div>
      </div>
      <SwiperPaginationBullets
        className="absolute bottom-2 left-[50%]"
        currentBullet={currentSlide}
        bulletCount={slides.length}
        handleOnBulletSwitch={handleOnSlideChange}
      />
    </div>
  );
};

export default MainPageSlider;
