import type { StoreSiteBlock } from "@alqove/api-client";
import { formatPrice } from "@alqove/shared";
import { blockData, bool, str } from "../block-data";
import { marketplaceUrl, type StorefrontRenderContext } from "../links";
import { SectionHeading, StorefrontSection } from "../section";
import type { StorefrontProduct } from "../products";

interface ProductsBlockProps {
  block: StoreSiteBlock;
  ctx: StorefrontRenderContext;
  /**
   * Resolved by the caller, not the block. A `products` block stores a query
   * (`source`, `category_slug`, `item_ids`, `limit`) rather than listings, and
   * keeping resolution outside lets the public page resolve on the server
   * while the seller's editor preview resolves in the browser.
   */
  products: StorefrontProduct[];
}

export function ProductsBlock({ block, ctx, products }: ProductsBlockProps) {
  const data = blockData(block);
  const storeId = ctx.shell.store?.id;
  const heading = str(data, "heading") ?? "Shop";
  const showViewAll = bool(data, "show_view_all", true) && Boolean(storeId);

  return (
    <StorefrontSection id="products">
      <div className="mb-6 flex items-end justify-between gap-4">
        <SectionHeading>{heading}</SectionHeading>
        {showViewAll && (
          <a
            href={marketplaceUrl(ctx.shell, `/stores/${storeId}`)}
            className="mb-6 shrink-0 text-sm font-medium underline underline-offset-4"
            style={{ color: "var(--sf-primary)" }}
          >
            View all
          </a>
        )}
      </div>

      {products.length === 0 ? (
        <p className="text-sm" style={{ color: "var(--sf-muted)" }}>
          Nothing listed here just yet — check back soon.
        </p>
      ) : (
        <ul className="grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
          {products.map((product) => (
            <li key={product.id}>
              <a
                href={marketplaceUrl(ctx.shell, `/items/${product.id}`)}
                className="group block"
              >
                <div
                  className="mb-3 aspect-[4/5] w-full overflow-hidden"
                  style={{
                    backgroundColor: "var(--sf-surface)",
                    borderRadius: "var(--sf-radius)",
                  }}
                >
                  {product.imageUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={product.imageUrl}
                      alt={product.title}
                      loading="lazy"
                      className="h-full w-full object-cover transition-transform duration-200 group-hover:scale-[1.03]"
                    />
                  ) : (
                    <div
                      className="flex h-full w-full items-center justify-center text-xs"
                      style={{ color: "var(--sf-muted)" }}
                    >
                      No image
                    </div>
                  )}
                </div>
                {product.brand && (
                  <p
                    className="text-xs font-medium uppercase tracking-wide"
                    style={{ color: "var(--sf-muted)" }}
                  >
                    {product.brand}
                  </p>
                )}
                <p className="line-clamp-2 text-sm font-medium">{product.title}</p>
                <p className="mt-1 text-sm font-semibold">{formatPrice(product.price)}</p>
                {product.condition && (
                  <p className="text-xs" style={{ color: "var(--sf-muted)" }}>
                    {product.condition}
                  </p>
                )}
              </a>
            </li>
          ))}
        </ul>
      )}
    </StorefrontSection>
  );
}
