"use client";

import React, { useMemo, useRef, useState } from "react";
import Image from "next/image";
import { Swiper, SwiperSlide } from "swiper/react";
import { Mousewheel } from "swiper/modules";

import "swiper/css";

import { withCDN } from "@/src/lib/utils";
import ImageLightbox from "../../ui/ImageLightbox";

type Photo = {
  id: string | number;
  src: string;
  alt: string;
};

export default function PhotosCarousel({
  photos,
}: {
  photos: Photo[];
}) {
  const swiperRef = useRef<any>(null);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  // Images passed to the shared ImageLightbox component
  const galleryImages = useMemo(
    () => photos.map((photo) => withCDN(photo.src)),
    [photos]
  );

  // Infinite carousel logic
  const MIN_SLIDES = 25;
  const MAX_REPEAT = 40;

  const extendedPhotos = useMemo(() => {
    if (!photos || photos.length === 0) return [];

    const repeatCount = Math.min(
      MAX_REPEAT,
      Math.max(1, Math.ceil(MIN_SLIDES / photos.length))
    );

    const list: Array<{ photo: Photo; r: number }> = [];

    for (let r = 0; r < repeatCount; r++) {
      for (let i = 0; i < photos.length; i++) {
        list.push({ photo: photos[i], r });
      }
    }

    return list;
  }, [photos]);

  return (
    <>
      <div className="relative mt-4 flex w-full items-center gap-2 discover-carousel">
        {/* LEFT BUTTON */}
        <button
          type="button"
          onClick={() => swiperRef.current?.slidePrev()}
          aria-label="Previous photos"
          className="mt-[-50px] flex-shrink-0 transition"
        >
          <Image
            src={withCDN("/arrow-left.svg")}
            alt="Previous"
            width={28}
            height={28}
            className="h-[24px] w-[24px] cursor-pointer md:h-[28px] md:w-[28px]"
            unoptimized
          />
        </button>

        {/* SWIPER */}
        <Swiper
          modules={[Mousewheel]}
          onSwiper={(swiper) => {
            swiperRef.current = swiper;
          }}
          onSetTranslate={(swiper) => {
            if (window.innerWidth >= 768) return;

            swiper.slides.forEach((slide, index) => {
              const slideEl = slide as HTMLElement;

              const slideOffset =
                swiper.slidesGrid[index] + swiper.translate;

              const distance = Math.min(
                Math.abs(slideOffset) / swiper.width,
                1
              );

              const scale = 1 - distance * 0.2;
              const opacity = 1 - distance * 0.2;

              slideEl.style.transform = `scale(${scale})`;
              slideEl.style.opacity = `${opacity}`;
            });
          }}
          onSetTransition={(swiper, duration) => {
            if (window.innerWidth >= 768) return;

            swiper.slides.forEach((slide) => {
              (slide as HTMLElement).style.transitionDuration =
                `${duration}ms`;
            });
          }}
          slidesPerView={1}
          spaceBetween={12}
          loop={true}
          grabCursor={true}
          mousewheel={{ forceToAxis: true }}
          slidesOffsetBefore={0}
          slidesOffsetAfter={0}
          breakpoints={{
            768: {
              slidesPerView: 3.5,
              spaceBetween: 16,
            },
            1024: {
              slidesPerView: 5,
              spaceBetween: 10,
              centeredSlides: false,
            },
          }}
          className="photos-carousel-swiper flex-grow overflow-hidden py-2"
        >
          {extendedPhotos.map(({ photo, r }, idx) => (
            <SwiperSlide
              key={`${photo.id}-${r}-${idx}`}
              className="flex-shrink-0 pb-2"
            >
              <button
                type="button"
                onClick={() => {
                  const index = photos.findIndex(
                    (item) => item.id === photo.id
                  );

                  if (index !== -1) {
                    setLightboxIndex(index);
                  }
                }}
                aria-label={`View ${photo.alt}`}
                className="
                  discover-slider-box
                  h-[90px] w-full
                  cursor-pointer
                  rounded-2xl
                  transition-transform
                  hover:mt-[4px]
                  hover:scale-105
                  sm:h-[100px]
                  md:h-[110px] md:w-[180px]
                  lg:h-[145px] lg:w-full
                "
                style={{
                  boxShadow: "9px 14px 14px rgba(0,0,0,0.15)",
                }}
              >
                <Image
                  src={withCDN(photo.src)}
                  alt={photo.alt}
                  width={232}
                  height={145}
                  className="h-full w-full rounded-2xl object-cover"
                />
              </button>
            </SwiperSlide>
          ))}
        </Swiper>

        {/* RIGHT BUTTON */}
        <button
          type="button"
          onClick={() => swiperRef.current?.slideNext()}
          aria-label="Next photos"
          className="
            mt-[-50px]
            mr-0
            flex-shrink-0
            rotate-180
            cursor-pointer
            rounded-[50%]
            bg-white
            transition
            xl:mr-0
          "
        >
          <Image
            src={withCDN("/arrow-left.svg")}
            alt="Next"
            width={28}
            height={28}
            className="h-[24px] w-[24px] md:h-[28px] md:w-[28px]"
            unoptimized
          />
        </button>
      </div>

      {/* SHARED LIGHTBOX */}
      <ImageLightbox
        images={galleryImages}
        index={lightboxIndex}
        onClose={() => setLightboxIndex(null)}
      />
    </>
  );
}
