"use client";

import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import ShopProductAuthor from "@/components/shops/ShopProductAuthor";
import { IShopProductListing } from "@/types/types";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";

type ShopProductGridProps = {
  listings: IShopProductListing[];
  /** Fallback shop name/logo used when `listing.shop` isn't a populated object (single-shop pages). */
  shopName?: string;
  shopLogo?: string | null;
  isLoading?: boolean;
  /** Defaults to the Torob-style price-comparison page for the listing's catalog product. */
  getHref?: (listing: IShopProductListing) => string;
};

function cheapestPrice(listing: IShopProductListing): number | null {
  if (!listing.variants || listing.variants.length === 0) return null;
  return Math.min(...listing.variants.map((v) => v.discount_price || v.price));
}

const ASPECT_RATIOS = [
  "aspect-[2/3]",
  "aspect-[3/4]",
  "aspect-[4/5]",
  "aspect-[5/6]",
  "aspect-square",
  "aspect-[3/5]",
] as const;

const SKELETON_COUNT = 8;

function hashAspect(id: string): (typeof ASPECT_RATIOS)[number] {
  let hash = 0;
  for (let i = 0; i < id.length; i++) {
    hash = (hash + id.charCodeAt(i)) % ASPECT_RATIOS.length;
  }
  return ASPECT_RATIOS[hash];
}

function defaultHref(listing: IShopProductListing): string {
  const catalogId =
    typeof listing.catalogProduct === "string"
      ? listing.catalogProduct
      : listing.catalogProduct?._id;
  return `/shops/product/${catalogId}`;
}

function ProductCardSkeleton({ aspect }: { aspect: string }) {
  return (
    <article className="mb-2 break-inside-avoid">
      <div
        className={`relative w-full animate-pulse overflow-hidden rounded-2xl bg-neutral-200 dark:bg-neutral-800 ${aspect}`}
      />
      <div className="flex flex-col gap-1 px-0.5 py-1.5">
        <div className="h-3 w-20 animate-pulse rounded-full bg-neutral-200 dark:bg-neutral-800" />
        <div className="h-3 w-14 animate-pulse rounded-full bg-neutral-200 dark:bg-neutral-800" />
      </div>
    </article>
  );
}

export default function ShopProductGrid({
  listings,
  shopName,
  shopLogo,
  isLoading,
  getHref = defaultHref,
}: ShopProductGridProps) {
  const { t } = useTranslation("common");
  const router = useRouter();

  if (isLoading) {
    return (
      <div className="px-2 pb-2">
        <div className="columns-2 gap-2">
          {Array.from({ length: SKELETON_COUNT }).map((_, index) => (
            <ProductCardSkeleton key={index} aspect={ASPECT_RATIOS[index % ASPECT_RATIOS.length]} />
          ))}
        </div>
      </div>
    );
  }

  if (!listings.length) {
    return (
      <p className="py-16 text-center text-sm text-neutral-500">
        {t("shops.noProductsYet")}
      </p>
    );
  }

  return (
    <div className="px-2 pb-2">
      <div className="columns-2 gap-2">
        {listings.map((listing) => {
          const primaryImage =
            listing.images?.[listing.primaryImageIndex] || listing.images?.[0];
          const price = cheapestPrice(listing);
          const cardShop =
            typeof listing.shop === "object" && listing.shop
              ? listing.shop
              : null;
          const aspect = hashAspect(listing._id);

          return (
            <article key={listing._id} className="mb-2 break-inside-avoid">
              <button
                type="button"
                onClick={() => router.push(getHref(listing))}
                className="gentle-transition block w-full text-right active:scale-[0.98]"
              >
                <div
                  className={`relative w-full overflow-hidden rounded-2xl bg-neutral-200 dark:bg-neutral-900 ${aspect}`}
                >
                  {primaryImage ? (
                    <Image
                      src={IMAGE_BASE_URL + primaryImage}
                      alt={listing.title}
                      fill
                      className="object-cover"
                      sizes="50vw"
                      unoptimized
                    />
                  ) : null}
                  {listing.status !== "active" && (
                    <span className="absolute left-2 top-2 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white">
                      {t(`shops.status.${listing.status}`)}
                    </span>
                  )}
                </div>
              </button>
              <div className="flex flex-col gap-1 px-0.5 py-1.5">
                <ShopProductAuthor
                  shopName={cardShop?.name || shopName || ""}
                  shopLogo={cardShop?.logo ?? shopLogo}
                />
                <span className="truncate text-xs font-semibold">
                  {listing.title}
                </span>
                {price != null && (
                  <span className="text-[11px] text-neutral-500">
                    {t("shops.priceLabel", {
                      amount: price.toLocaleString(),
                    })}
                  </span>
                )}
                {listing.shop_count != null && listing.shop_count > 1 && (
                  <span className="text-[11px] font-medium text-[#387E65]">
                    {t("shops.availableInShopsCount", { count: listing.shop_count })}
                  </span>
                )}
              </div>
            </article>
          );
        })}
      </div>
    </div>
  );
}
