"use client";

import useEmblaCarousel from "embla-carousel-react";
import { useCallback } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { motion } from "framer-motion";

interface Category {
  id: number;
  name: string;
  icon?: string;
  product_count?: number;
}

interface CategorySliderProps {
  categories: Category[];
  activeId: number | null;
  onSelect: (id: number | null) => void;
}

export default function CategorySlider({ categories, activeId, onSelect }: CategorySliderProps) {
  const [emblaRef, emblaApi] = useEmblaCarousel({
    align: "start",
    dragFree: true,
    containScroll: "trimSnaps",
  });

  const scrollPrev = useCallback(() => emblaApi?.scrollPrev(), [emblaApi]);
  const scrollNext = useCallback(() => emblaApi?.scrollNext(), [emblaApi]);

  const allCategories = [{ id: 0, name: "✨ Tümü", icon: "✨" }, ...categories];

  return (
    <div className="relative group">
      {/* Left Arrow */}
      <button
        onClick={scrollPrev}
        className="absolute left-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 bg-background/80 backdrop-blur rounded-full shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity -translate-x-2"
      >
        <ChevronLeft className="w-4 h-4" />
      </button>

      <div className="embla" ref={emblaRef}>
        <div className="embla__container gap-2 px-1">
          {allCategories.map((cat) => {
            const isActive = cat.id === 0 ? activeId === null : activeId === cat.id;
            return (
              <div key={cat.id} className="embla__slide">
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => onSelect(cat.id === 0 ? null : cat.id)}
                  className={`relative flex items-center gap-2 px-4 py-2.5 rounded-full text-sm font-medium whitespace-nowrap transition-all duration-300 ${
                    isActive
                      ? "bg-primary text-primary-foreground shadow-lg shadow-primary/25"
                      : "bg-muted text-muted-foreground hover:bg-accent hover:text-accent-foreground"
                  }`}
                >
                  <span className="text-base">{cat.icon || "📁"}</span>
                  <span>{cat.name.replace(/^[^\s]+\s/, "")}</span>
                </motion.button>
              </div>
            );
          })}
        </div>
      </div>

      {/* Right Arrow */}
      <button
        onClick={scrollNext}
        className="absolute right-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 bg-background/80 backdrop-blur rounded-full shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity translate-x-2"
      >
        <ChevronRight className="w-4 h-4" />
      </button>
    </div>
  );
}
