import Image from "next/image";
import Link from "next/link";
import type {
  HomepageProductItem,
  HomepageProductsSettings,
  ImageAsset,
  Locale,
  Product,
} from "@/types/content";
import { getImageAlt, getImageUrl } from "@/lib/images";
import { sortProductsByShowroomOrder } from "@/lib/product-order";
import { localizedPath } from "@/lib/routing";

type HomeProductShowcaseProps = {
  locale: Locale;
  products?: HomepageProductsSettings;
  productItems?: Product[];
};

type DisplayProduct = HomepageProductItem | Product;

export function HomeProductShowcase({
  locale,
  products,
  productItems,
}: HomeProductShowcaseProps) {
  const items: DisplayProduct[] = productItems?.length
    ? sortProductsByShowroomOrder(productItems)
    : products?.items ?? [];

  if (!items.length) return null;

  const eyebrow =
    products?.eyebrow?.[locale] ||
    (locale === "id" ? "Produk" : "Products");

  const title =
    products?.title?.[locale] ||
    (locale === "id"
      ? "Produk teknologi untuk ruang yang andal."
      : "Technology products for reliable spaces.");

  const intro = products?.intro?.[locale];

  return (
    <section className="home-products-section" id="products">
      <div className="home-products-header">
        <p className="eyebrow">{eyebrow}</p>
        <h2>{title}</h2>
        {intro ? <p>{intro}</p> : null}
      </div>

      <div className="home-products-showcase">
        {items.map((item, index) => (
          <ProductCard
            key={getProductKey(item, index)}
            item={item}
            locale={locale}
            index={index}
          />
        ))}
      </div>
    </section>
  );
}

function ProductCard({
  item,
  locale,
  index,
}: {
  item: DisplayProduct;
  locale: Locale;
  index: number;
}) {
  const image = getProductImage(item);
  const imageUrl = getImageUrl(image);
  const title = item.title[locale];
  const href = getProductHref(item, locale);

  return (
    <Link
      className={`home-product-card home-product-card-${index + 1}`}
      prefetch={false}
      href={href}
      aria-label={title}
    >
      <div className="home-product-content">
        <h3>{title}</h3>

        <span className="home-product-arrow" aria-hidden="true">
          →
        </span>
      </div>

      <div
        className="home-product-media"
        aria-hidden={!imageUrl}
      >
        {imageUrl ? (
          <Image
            src={imageUrl}
            alt={getImageAlt(image, title)}
            fill
            sizes="
              (max-width: 700px) 100vw,
              (max-width: 1100px) 50vw,
              25vw
            "
          />
        ) : (
          <span>{title}</span>
        )}
      </div>
    </Link>
  );
}

function getProductKey(item: DisplayProduct, index: number) {
  return "_key" in item && item._key
    ? item._key
    : "slug" in item
      ? item.slug
      : `${item.title.en}-${index}`;
}

function getProductImage(
  item: DisplayProduct
): ImageAsset | undefined {
  if ("showcaseImage" in item && item.showcaseImage) return item.showcaseImage;
  if ("heroImage" in item) return item.heroImage;
  if ("image" in item) return item.image;

  return undefined;
}

function getProductHref(
  item: DisplayProduct,
  locale: Locale
) {
  if ("slug" in item) {
    return localizedPath(`/products/${item.slug}`, locale);
  }

  return normalizeProductHref(item.href, locale);
}

function normalizeProductHref(
  href: string | undefined,
  locale: Locale
) {
  if (!href) {
    return localizedPath("/products", locale);
  }

  if (
    href.startsWith("http://") ||
    href.startsWith("https://")
  ) {
    return href;
  }

  return localizedPath(
    href.startsWith("/") ? href : `/${href}`,
    locale
  );
}