"use client";

import Image from "next/image";
import Link from "next/link";
import {
  AppWindow,
  Boxes,
  Laptop,
  LayoutGrid,
  Monitor,
  Network,
  Presentation,
  Projector,
  ScanLine,
  Server,
  Volume2,
  type LucideIcon
} from "lucide-react";
import { useMemo, useState } from "react";
import { getImageAlt, getImageUrl } from "@/lib/images";
import { getProductInitial, sortProductsByShowroomOrder } from "@/lib/product-order";
import { localizedPath } from "@/lib/routing";
import type { Locale, Product, ProductCategory } from "@/types/content";

type ProductCatalogProps = {
  locale: Locale;
  products: Product[];
  categories: ProductCategory[];
};

const ALL = "all";

const CATEGORY_ICONS: Record<string, LucideIcon> = {
  "interactive-flat-panel": Presentation,
  "commercial-display": Monitor,
  "led-videotron": ScanLine,
  projector: Projector,
  "professional-sound": Volume2,
  server: Server,
  network: Network,
  "pc-and-laptop": Laptop,
  software: AppWindow
};

function iconFor(slug: string): LucideIcon {
  return CATEGORY_ICONS[slug] ?? Boxes;
}

export function ProductCatalog({ locale, products, categories }: ProductCatalogProps) {
  const ordered = useMemo(() => sortProductsByShowroomOrder(products), [products]);

  // Category order + copy comes from the CMS `product-categories` module. When
  // that endpoint is unavailable, fall back to the category reference embedded
  // in each product, in product (showroom) order.
  const catalog = useMemo(
    () =>
      (categories.length ? categories : deriveCategories(ordered)).filter((category) =>
        ordered.some((product) => product.category?.slug === category.slug)
      ),
    [categories, ordered]
  );

  const [active, setActive] = useState<string>(ALL);
  const activeExists = active === ALL || catalog.some((category) => category.slug === active);
  const current = activeExists ? active : ALL;

  const visible = useMemo(
    () => (current === ALL ? ordered : ordered.filter((product) => product.category?.slug === current)),
    [current, ordered]
  );

  if (!ordered.length) return null;

  const navTitle = locale === "id" ? "Kategori Produk" : "Product Categories";
  const tabs = [
    { key: ALL, label: locale === "id" ? "Semua Produk" : "All Products", Icon: LayoutGrid },
    ...catalog.map((category) => ({
      key: category.slug,
      label: category.title?.[locale] ?? category.slug,
      Icon: iconFor(category.slug)
    }))
  ];

  return (
    <section className="product-catalog" aria-label={locale === "id" ? "Katalog produk Akarya" : "Akarya product catalog"}>
      <div className="container">
        <nav className="product-catalog-nav" aria-label={navTitle}>
          <div className="product-catalog-nav-list" role="tablist">
            {tabs.map(({ key, label, Icon }) => {
              const isActive = current === key;
              return (
                <button
                  key={key}
                  type="button"
                  role="tab"
                  aria-selected={isActive}
                  className={`product-catalog-nav-item${isActive ? " is-active" : ""}`}
                  onClick={() => setActive(key)}
                >
                  <span className="product-catalog-nav-tile">
                    <Icon size={40} strokeWidth={1.25} aria-hidden="true" />
                  </span>
                  <span className="product-catalog-nav-label">{label}</span>
                </button>
              );
            })}
          </div>
        </nav>

        <div className="product-catalog-grid">
          {visible.map((product, index) => (
            <ProductCard key={product.slug} product={product} locale={locale} index={index} />
          ))}
        </div>
      </div>
    </section>
  );
}

/** Unique categories in first-seen (showroom) order, from the product references. */
function deriveCategories(products: Product[]): ProductCategory[] {
  const seen = new Map<string, ProductCategory>();
  products.forEach((product, index) => {
    const category = product.category;
    if (category?.slug && category.title && !seen.has(category.slug)) {
      seen.set(category.slug, { slug: category.slug, title: category.title, position: index + 1 });
    }
  });
  return [...seen.values()];
}

function ProductCard({ product, locale, index }: { product: Product; locale: Locale; index: number }) {
  const image = product.heroImage ?? product.showcaseImage;
  const imageUrl = getImageUrl(image);
  const title = product.title[locale];
  const eyebrow = product.category?.title?.[locale];

  return (
    <Link className="product-cat-card" href={localizedPath(`/products/${product.slug}`, locale)}>
      <div className="product-cat-media" aria-hidden={!imageUrl}>
        {imageUrl ? (
          <Image
            src={imageUrl}
            alt={getImageAlt(image, title)}
            fill
            sizes="(max-width: 640px) 100vw, (max-width: 1100px) 45vw, 30vw"
          />
        ) : (
          <span>{getProductInitial(product.title.en, index)}</span>
        )}
      </div>
      <div className="product-cat-body">
        {eyebrow ? <p className="eyebrow">{eyebrow}</p> : null}
        <h3>{title}</h3>
        <p>{product.shortDescription[locale]}</p>
        <span className="product-cat-link">
          {locale === "id" ? "Pelajari Selengkapnya" : "Learn More"} <span aria-hidden="true">›</span>
        </span>
      </div>
    </Link>
  );
}
