'use client';

import Image from "next/image";
import clsx from "clsx";
import HorizontalScrollView from "@/components/listview/HorizontalScrollView";
import CategoryItemRenderer from "@/components/listview/CategoryItemRenderer";
import CategorySmallItemRenderer from "@/components/listview/CategorySmallItemRenderer";
import { Category } from "@/app/[name]/(Main)/types/Types";

type Variant = "large" | "small";

const variantConfig: Record<
  Variant,
  {
    renderer: typeof CategoryItemRenderer;
    imageSize: number;
  }
> = {
  large: {
    renderer: CategoryItemRenderer,
    imageSize: 32,
  },
  small: {
    renderer: CategorySmallItemRenderer,
    imageSize: 24,
  },
};

type Props = {
  categories: Category[];
  selectedCategory: string;
  onSelect: (index: number) => void;
  variant?: Variant;
  className?: string;
};

const CategoryScroll = ({
  categories,
  selectedCategory,
  onSelect,
  variant = "large",
  className,
}: Props) => {
  const { renderer: Renderer, imageSize } = variantConfig[variant];

  const handleSelect = (index: number) => () => onSelect(index);

  return (
    <HorizontalScrollView
      className={clsx(
        "w-full noscrollbar py-4!",
        variant === "large" && "mt-4!",
        className
      )}
    >
      <Renderer
        key="all"
        className={clsx(selectedCategory === "0" && "bg-container!")}
        onClick={handleSelect(0)}
      >
        <Image
          priority
          src="/assets/images/food-image.png"
          width={imageSize}
          height={imageSize}
          alt="category image"
        />
        <span className="text-xs text-foreground">همه</span>
      </Renderer>
      {categories.map((item, index) => {
        const categoryIndex = index + 1;
        const isSelected = String(categoryIndex) === selectedCategory;

        return (
          <Renderer
            key={item.id}
            className={clsx(isSelected && "bg-container!")}
            onClick={handleSelect(categoryIndex)}
          >
            <Image
              priority
              src={item.avatarUrl || "/assets/images/food-image.png"}
              width={imageSize}
              height={imageSize}
              alt="category image"
            />
            <span className="text-xs text-foreground">{item.title}</span>
          </Renderer>
        );
      })}
    </HorizontalScrollView>
  );
};

export default CategoryScroll;

