"use client";

import CarouselComponent from "@/components/carousel-component";
import ProductCard from "@/components/ProductCard";
import React from "react";
import { SwiperSlide } from "swiper/react";
import { useAppDispatch } from "@/store/hooks";
import { addToCart, setCartOpen } from "@/store/slices/cart-slice";
import { mapProductFromApi } from "@/lib/mappers/product-mapper";
import toast from "react-hot-toast";
import { useTranslations } from "next-intl";

export default function ProductsCarousel({ products }: { products: any[] }) {
  const dispatch = useAppDispatch();
  const tProducts = useTranslations("products");

  if (!products || !Array.isArray(products) || products.length === 0) {
    return null;
  }

  const handleAddToCart = async (productId: number) => {
    try {
      await dispatch(addToCart({ productId, productQTY: 1 })).unwrap();
      toast.success(tProducts("added-to-cart"));
      dispatch(setCartOpen(true));
    } catch (error: any) {
      toast.error(error?.message || tProducts("failed-to-add-to-cart"));
      throw error;
    }
  };

  // Limit to 8 products (2 rows x 4 columns on large screens)
  const displayedProducts = products.slice(0, 8);

  return (
    <CarouselComponent
      containerClassName="w-full h-auto"
      spaceBetween={6}
      slidesPerView={1}
      autoHeight
      breakpoints={{
        300: {
          slidesPerView: 2,
          slidesPerColumn: 2,
          spaceBetween: 4,
        },
        350: {
          slidesPerView: 2,
          slidesPerColumn: 2,
          spaceBetween: 4,
        },
        700: {
          slidesPerView: 3,
          slidesPerColumn: 2,
          spaceBetween: 4,
        },
        1200: {
          slidesPerView: 4,
          slidesPerColumn: 2,
          spaceBetween: 6,
        },
        1500: {
          slidesPerView: 5,
          slidesPerColumn: 2,
          spaceBetween: 6,
        },
        1800: {
          slidesPerView: 6,
          slidesPerColumn: 2,
          spaceBetween: 6,
        },
      }}
      autoPlay={true}
      autoplayDelay={5000}
    >
      {displayedProducts.map((rawProduct: any, index: number) => {
        const product = mapProductFromApi(rawProduct);
        return (
          <SwiperSlide key={product?.id || index}>
            <ProductCard 
              product={product} 
              onAddToCart={handleAddToCart}
            />
          </SwiperSlide>
        );
      })}
    </CarouselComponent>
  );
}
