"use client";

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

/** TODO: remove when backend sends avatarRenderMode */
const COLORED_SVG_RESTAURANT_SLUGS = new Set(["havasone"]);

const SVG_MASK_STYLE = {
  maskSize: "contain",
  maskRepeat: "no-repeat",
  maskPosition: "center",
  WebkitMaskSize: "contain",
  WebkitMaskRepeat: "no-repeat",
  WebkitMaskPosition: "center",
} as const;

function CategoryImage({ src, size, alt, tintWithPrimary = true }: { src: string; size: number; alt: string; tintWithPrimary?: boolean }) {
  const isSvg = src.endsWith(".svg");
  const shouldUseSvgMask = isSvg && tintWithPrimary;

  if (shouldUseSvgMask) {
    return (
      <div
        className="shrink-0 bg-primary"
        style={{
          width: size,
          height: size,
          maskImage: `url(${src})`,
          WebkitMaskImage: `url(${src})`,
          ...SVG_MASK_STYLE,
        }}
        role="img"
        aria-label={alt}
      />
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      width={size}
      height={size}
      alt={alt}
      loading="lazy"
      className="shrink-0 object-contain"
      onError={(event) => {
        event.currentTarget.src = "/assets/images/food-image.png";
      }}
    />
  );
}

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: (categoryId: string) => void;
  variant?: Variant;
  className?: string;
};

const CategoryScroll = ({ categories, selectedCategory, onSelect, variant = "large", className }: Props) => {
  const segment = usePathname()?.split("/").filter(Boolean)[0];
  const usesColoredSvg = segment != null && COLORED_SVG_RESTAURANT_SLUGS.has(segment.toLowerCase());
  const { renderer: Renderer, imageSize } = variantConfig[variant];
  const selectedParent = categories.find((c) => c.id === selectedCategory) ?? categories.find((c) => c.children?.some((ch) => ch.id === selectedCategory));
  const children = selectedParent?.children ?? [];

  const handleSelect = (categoryId: string) => () => onSelect(categoryId);

  return (
    <div className="flex flex-col">
      <HorizontalScrollView
        className={clsx(
          "w-full noscrollbar",
          children.length > 0 ? "pt-4! pb-1!" : "py-4!",
          // variant === "large" && "mt-4!",
          className,
        )}
      >
        {categories.map((item) => {
          const isSelected = item.id === selectedCategory || item.children?.some((ch) => ch.id === selectedCategory);

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

      {children.length > 0 && (
        <HorizontalScrollView className={clsx("w-full noscrollbar py-2!", variant === "small" && "py-1!")}>
          {children.map((child) => {
            const isChildSelected = child.id === selectedCategory;

            return (
              <CategorySmallItemRenderer key={child.id} compact className={clsx(isChildSelected && "bg-container!")} onClick={handleSelect(child.id)}>
                {child.avatarUrl && <CategoryImage src={child.avatarUrl} size={16} alt="category image" tintWithPrimary={!usesColoredSvg} />}
                <span className="text-[10px] text-foreground whitespace-nowrap">{child.title}</span>
              </CategorySmallItemRenderer>
            );
          })}
        </HorizontalScrollView>
      )}
    </div>
  );
};

export default CategoryScroll;
