"use client";

import { useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import Slider from "react-slick";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useHomeData } from "@/context/helpers/Home";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";

function CollectionArrow({ onClick, direction, className }) {
  const isPrev = direction === "prev";

  return (
    <button
      type="button"
      onClick={onClick}
      aria-label={isPrev ? "Previous slide" : "Next slide"}
      className={cn(
        "top-1/2 z-10 absolute flex justify-center items-center",
        "bg-white/20 hover:bg-white/30 rounded-full size-12 md:size-[59px]",
        "text-white transition-colors -translate-y-1/2",
        "[&.slick-disabled]:opacity-35 [&.slick-disabled]:pointer-events-none",
        isPrev ? "inset-s-4 md:inset-s-5" : "inset-e-4 md:inset-e-5",
        className
      )}
    >
      {isPrev ? (
        <ChevronLeft className="size-6 md:size-7" strokeWidth={2} />
      ) : (
        <ChevronRight className="size-6 md:size-7" strokeWidth={2} />
      )}
    </button>
  );
}

function mapSlideItem(item, index) {
  const image = item.image || item.url || item.thumbNail;
  if (!image) return null;

  const productCount =
    item.productCount ??
    item.productsCount ??
    item.products_count ??
    item.count ??
    null;

  return {
    id: item.id ?? index,
    image,
    title: item.title || item.name || "",
    subtitle: item.description || item.subtitle || item.desc || "",
    productCount:
      productCount !== null && productCount !== undefined
        ? Number(productCount)
        : null,
    link: item.link || item.url_link || "/",
  };
}

export default function CollectionsCarousel({
  showTitle = true,
  showBackground = true,
  className = "",
}) {
  const { ads } = useHomeData();
  const { t, i18n } = useTranslation("home");
  const isArabic = i18n.language?.startsWith("ar");

  const dotButtonClass = showBackground
    ? "bg-white/40"
    : "bg-gray-300 dark:bg-gray-600";

  const settings = useMemo(
    () => ({
      dots: ads.length > 1,
      infinite: ads.length > 1,
      speed: 500,
      autoplay: true,
      autoplaySpeed: 4000,
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: ads.length > 1,
      rtl: isArabic,
      nextArrow: <CollectionArrow direction="next" />,
      prevArrow: <CollectionArrow direction="prev" />,
      appendDots: (dots) => (
        <ul className="flex justify-center gap-0 mt-6 leading-none static!">
          {dots}
        </ul>
      ),
      customPaging: () => (
        <button
          type="button"
          className={cn(
            "before:hidden block p-0 rounded-full w-2.5 h-2.5 transition-all duration-200 ease-in-out",
            dotButtonClass
          )}
          aria-hidden
          tabIndex={-1}
        />
      ),
    }),
    [ads.length, isArabic, dotButtonClass]
  );

  if (ads.length === 0) return null;

  return (
    <section
      className={cn(
        "py-12 md:py-16 lg:py-20",
        showBackground && "bg-mainColor",
        className
      )}
    >
      <div className="mx-auto px-4 md:px-8 lg:px-12 max-w-[1259px] container">
        {showTitle ? (
          <h2
            className={cn(
              "mb-10 md:mb-14 lg:mb-[59px] font-normal md:text-[37px] text-3xl text-center leading-tight",
              showBackground
                ? "text-white"
                : "text-[#253D4E] dark:text-gray-100"
            )}
          >
            {t("layout11.collectionsTitle")}
          </h2>
        ) : null}

        <div
          className={cn(
            "relative",
            "[&_.slick-dots_li]:w-auto [&_.slick-dots_li]:h-auto [&_.slick-dots_li]:mx-[5px]",
            "[&_.slick-dots_li.slick-active_button]:w-10",
            showBackground
              ? "[&_.slick-dots_li.slick-active_button]:bg-white"
              : "[&_.slick-dots_li.slick-active_button]:bg-mainColor"
          )}
        >
          <Slider {...settings}>
            {ads.map((slide) => (
              <div key={slide.id} className="outline-none">
                <Link
                  href={slide.link}
                  className="group block relative bg-mainColor/80 rounded-[20px] md:rounded-[30px] aspect-[1210/523] overflow-hidden"
                >
                  <Image
                    src={slide.url}
                    alt={slide.title || ""}
                    fill
                    className="object-cover"
                    sizes="(max-width: 768px) 100vw, 1220px"
                  />

                  <div
                    className="absolute inset-0 bg-linear-to-t from-black/80 via-black/40 to-transparent rounded-[20px] md:rounded-[30px]"
                    aria-hidden
                  />

                  <div
                    dir={isArabic ? "rtl" : "ltr"}
                    className="absolute inset-0 flex flex-col justify-center px-6 md:px-12 lg:px-[59px] py-10 pointer-events-none"
                  >
                    {slide.title ? (
                      <h3 className="mb-3 md:mb-4 font-normal text-white lg:text-[59px] text-3xl md:text-5xl text-start leading-tight lg:leading-[59px]">
                        {slide.title}
                      </h3>
                    ) : null}

                    {slide.subtitle ? (
                      <p className="mb-2 md:mb-3 max-w-3xl font-normal text-[#e5e7eb] lg:text-[25px] text-base md:text-xl text-start leading-relaxed lg:leading-[34px]">
                        {slide.subtitle}
                      </p>
                    ) : null}

                    {slide.productCount != null &&
                    !Number.isNaN(slide.productCount) ? (
                      <p className="mb-5 md:mb-6 font-normal text-[#d1d5dc] lg:text-[17px] text-sm md:text-base text-start leading-normal">
                        {t("layout11.collectionsProducts", {
                          count: slide.productCount,
                        })}
                      </p>
                    ) : null}
                  </div>
                </Link>
              </div>
            ))}
          </Slider>
        </div>
      </div>
    </section>
  );
}
