"use client";

import { type PropsWithChildren, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { cn } from "@/lib/cn";
import { detonexFigmaAssets } from "@/lib/detonex-figma";

interface FeaturedProductsRailProps extends PropsWithChildren {
  itemCount: number;
}

export function FeaturedProductsRail({
  itemCount,
  children,
}: FeaturedProductsRailProps) {
  const trackRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(itemCount > 4);

  useEffect(() => {
    const track = trackRef.current;

    if (!track) {
      return;
    }

    const updateScrollState = () => {
      const maxScrollLeft = track.scrollWidth - track.clientWidth;

      setCanScrollLeft(track.scrollLeft > 8);
      setCanScrollRight(track.scrollLeft < maxScrollLeft - 8);
    };

    updateScrollState();
    track.addEventListener("scroll", updateScrollState, { passive: true });
    window.addEventListener("resize", updateScrollState);

    return () => {
      track.removeEventListener("scroll", updateScrollState);
      window.removeEventListener("resize", updateScrollState);
    };
  }, [itemCount]);

  const scrollByCard = (direction: 1 | -1) => {
    const track = trackRef.current;

    if (!track) {
      return;
    }

    const firstCard = track.firstElementChild as HTMLElement | null;

    if (!firstCard) {
      return;
    }

    const cardWidth = firstCard.getBoundingClientRect().width;
    const trackStyles = window.getComputedStyle(track);
    const gap = Number.parseFloat(trackStyles.columnGap || trackStyles.gap || "0");
    const step = Math.round(cardWidth + gap);

    track.scrollBy({
      left: direction * step,
      behavior: "smooth",
    });
  };

  return (
    <div className="relative">
      <div
        ref={trackRef}
        className={cn(
          "flex gap-5 overflow-x-auto scroll-smooth pb-3 snap-x snap-mandatory",
          "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        )}
      >
        {children}
      </div>

      <div className="pointer-events-none absolute inset-y-0 left-0 right-0 hidden items-center justify-between xl:flex">
        <button
          type="button"
          aria-label="Prethodni proizvodi"
          onClick={() => scrollByCard(-1)}
          disabled={!canScrollLeft}
          className={cn(
            "pointer-events-auto -translate-x-1/2 inline-flex size-[42px] items-center justify-center rounded-full border border-black/10 bg-white transition-opacity",
            !canScrollLeft && "opacity-0",
          )}
        >
          <Image
            src={detonexFigmaAssets.icons.productSliderArrow}
            alt=""
            width={18}
            height={18}
            className="size-[18px] rotate-180"
          />
        </button>

        <button
          type="button"
          aria-label="Sljedeći proizvodi"
          onClick={() => scrollByCard(1)}
          disabled={!canScrollRight}
          className={cn(
            "pointer-events-auto translate-x-1/2 inline-flex size-[42px] items-center justify-center rounded-full border border-black/10 bg-white transition-opacity",
            !canScrollRight && "opacity-0",
          )}
        >
          <Image
            src={detonexFigmaAssets.icons.productSliderArrow}
            alt=""
            width={18}
            height={18}
            className="size-[18px]"
          />
        </button>
      </div>
    </div>
  );
}
