"use client";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
} from "@/components/ui/carousel";
import { useSettings } from "@/stores/settings";
import clsx from "clsx";
import Autoplay from "embla-carousel-autoplay";
import { useLocale } from "next-intl";
import { useEffect, useState } from "react";
import ProductCard from "../shared/ProductCard";
import SectionHeader from "../shared/SectionHeader";
export default function RelativeProducts({ products }) {
  const [api, setApi] = useState();
  const [currentSlide, setCurrentSlide] = useState(0);
  const locale = useLocale();
  const [totalSlides, setTotalSlides] = useState();
  const { settings } = useSettings();
  useEffect(() => {
    if (!api) {
      return;
    }
    setTotalSlides(api.slideNodes().length);
    api.on("select", () => {
      setCurrentSlide(api.selectedScrollSnap());
    });
  }, [api]);
  return (
    <>
      {products?.length > 0 ? (
        <div className="space-y-6">
          <SectionHeader
            title={locale == "ar" ? "منتجات" : "Similar"}
            marker={locale == "ar" ? "مشابهه" : "Products"}
            withLink={false}
          />
          <Carousel
            className="w-full "
            setApi={setApi}
            dir="ltr"
            opts={{
              loop: true,
              startIndex: 3,
              align: "start",
            }}
            plugins={[
              Autoplay({
                delay: 2500,
              }),
            ]}
          >
            <CarouselContent>
              {products?.map((product) => (
                <CarouselItem
                  key={product.id}
                  className="md:basis-1/2 lg:basis-1/3 "
                >
                  <div className="p-2">
                    <ProductCard product={product} />
                  </div>
                </CarouselItem>
              ))}
            </CarouselContent>
            <div className="flex justify-center mt-4 gap-2 overflow-x-auto pb-2">
              {Array.from({ length: totalSlides }).map((_, index) => (
                <button
                  key={index}
                  className={clsx(
                    `size-2 rounded-sm bg-gray-400 transition-all duration-300 flex-shrink-0`,
                    {
                      "bg-main h-2 w-8": index === currentSlide,
                    }
                  )}
                  onClick={() => api?.scrollTo(index)}
                />
              ))}
            </div>
          </Carousel>
        </div>
      ) : (
        ""
      )}
    </>
  );
}
