"use client";

import { useState, type CSSProperties } from "react";
import Link from "next/link";
import Image from "next/image";
import type { Product } from "@/types";
import { formatPrice, resolveMediaUrl, categoryDisplayName } from "@/lib/utils";
import ColorSwatch from "@/components/ui/ColorSwatch";
import type { TemplateConfig } from "@/lib/template";
import { useWishlistStore } from "@/lib/wishlist-store";
import { useCartStore } from "@/lib/cart-store";
import { useAuthStore, getAuthHeaders } from "@/lib/auth-store";
import { useLanguage } from "@/lib/language-context";

interface ProductCardProps {
  product: Product;
  currency?: string;
  template?: TemplateConfig;
}

function CatalogPrice({
  product,
  currency,
  className,
  style,
  variant = "default",
}: {
  product: Product;
  currency: string;
  className?: string;
  style?: CSSProperties;
  variant?: "default" | "onDark";
}) {
  const max = product.price_max;
  const sep =
    variant === "onDark" ? "text-white/65 font-normal mx-1" : "text-gray-500 font-normal mx-1";
  if (max != null && max > product.price) {
    return (
      <p className={className} style={style}>
        {formatPrice(product.price, currency)}
        <span className={sep}>–</span>
        {formatPrice(max, currency)}
      </p>
    );
  }
  return (
    <p className={className} style={style}>
      {formatPrice(product.price, currency)}
    </p>
  );
}

function CatalogVariantRow({ product }: { product: Product }) {
  const colors =
    product.colors_preview && product.colors_preview.length > 0
      ? product.colors_preview
      : product.color
        ? [product.color]
        : [];
  const sizes =
    product.sizes_preview && product.sizes_preview.length > 0
      ? product.sizes_preview
      : product.size
        ? [product.size]
        : [];

  return (
    <div className="flex flex-col gap-2">
      {colors.length > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          {colors.slice(0, 6).map((c) => (
            <ColorSwatch
              key={c.id}
              name={c.name}
              hex={c.hex ?? c.code}
              size="sm"
            />
          ))}
          {colors.length > 6 && (
            <span className="text-xs text-gray-500">+{colors.length - 6}</span>
          )}
        </div>
      )}
      {sizes.length > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          {sizes.slice(0, 8).map((s) => (
            <span
              key={s.id}
              className="text-xs text-gray-600 border border-gray-200 rounded-md px-2 py-0.5 font-medium"
            >
              {s.name}
            </span>
          ))}
          {sizes.length > 8 && (
            <span className="text-xs text-gray-500">+{sizes.length - 8}</span>
          )}
        </div>
      )}
      {!colors.length &&
        !sizes.length &&
        product.variant_label && (
          <p className="text-xs text-gray-500">{product.variant_label}</p>
        )}
    </div>
  );
}

function CatalogPrimaryAction({
  product,
  tone = "light",
}: {
  product: Product;
  tone?: "light" | "onDark";
}) {
  const { t } = useLanguage();
  if (!product.in_stock) return null;
  if (product.requires_variant_selection) {
    const cls =
      tone === "onDark"
        ? "text-xs font-semibold py-2.5 px-4 rounded-lg border border-white/40 text-white bg-white/10 backdrop-blur-sm"
        : "text-xs font-semibold py-2.5 px-4 rounded-lg border border-gray-200 text-gray-700 bg-white";
    return (
      <span className={cls} onClick={(e) => e.stopPropagation()}>
        {t.product.selectVariant}
      </span>
    );
  }
  return (
    <div onClick={(e) => e.stopPropagation()}>
      <AddToCartButton product={product} />
    </div>
  );
}

export default function ProductCard({
  product,
  currency = "EGP",
  template,
}: ProductCardProps) {
  const { locale } = useLanguage();
  const cardStyle = template?.cardStyle ?? "rounded";

  switch (cardStyle) {
    case "sharp":
      return (
        <CardSharp product={product} currency={currency} locale={locale} />
      );
    case "overlay":
      return (
        <CardOverlay product={product} currency={currency} locale={locale} />
      );
    case "minimal":
      return (
        <CardMinimal product={product} currency={currency} locale={locale} />
      );
    case "magazine":
      return (
        <CardMagazine product={product} currency={currency} locale={locale} />
      );
    default:
      return (
        <CardRounded product={product} currency={currency} locale={locale} />
      );
  }
}

// ── Classic: rounded card ─────────────────────────────────────────────────────
function CardRounded({
  product,
  currency,
  locale,
}: {
  product: Product;
  currency: string;
  locale: string;
}) {
  return (
    <Link
      href={`/products/${product.barcode}`}
      className="group bg-white rounded-xl border border-gray-200 overflow-hidden card-hover-lift flex flex-col"
    >
      <div className="aspect-square bg-gray-50 relative overflow-hidden">
        <ProductImage product={product} />
        <OutOfStockBadge product={product} />
        <WishlistButton product={product} />
        {product.category && (
          <span
            className="absolute bottom-3 left-3 text-xs font-semibold px-2.5 py-1 rounded-full bg-white/90 backdrop-blur-sm text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity"
            dir={locale?.startsWith("ar") ? "rtl" : undefined}
          >
            {categoryDisplayName(product.category, locale)}
          </span>
        )}
      </div>
      <div className="p-4 flex flex-col gap-2 flex-1">
        <p className="text-sm font-semibold text-gray-900 line-clamp-2 leading-snug group-hover:text-gray-700 transition-colors">
          {product.name}
        </p>
        <CatalogVariantRow product={product} />
        <div className="flex items-center justify-between mt-auto pt-3 gap-2">
          <CatalogPrice
            product={product}
            currency={currency}
            className="text-lg font-bold"
            style={{ color: "var(--color-primary)" }}
          />
          <CatalogPrimaryAction product={product} />
        </div>
      </div>
    </Link>
  );
}

// ── Marketplace: sharp edges, no border-radius ────────────────────────────────
function CardSharp({
  product,
  currency,
  locale,
}: {
  product: Product;
  currency: string;
  locale: string;
}) {
  return (
    <Link
      href={`/products/${product.barcode}`}
      className="group bg-white border border-gray-200 overflow-hidden hover:border-gray-400 hover:shadow-lg transition-all flex flex-col"
    >
      <div className="aspect-square bg-gray-50 relative overflow-hidden">
        <ProductImage product={product} />
        <OutOfStockBadge product={product} />
        <WishlistButton product={product} />
        {product.category && (
          <span
            className="absolute top-3 left-3 bg-white text-xs font-bold px-2.5 py-1 uppercase tracking-wide text-gray-800 shadow-sm"
            dir={locale?.startsWith("ar") ? "rtl" : undefined}
          >
            {categoryDisplayName(product.category, locale)}
          </span>
        )}
      </div>
      <div className="p-4 border-t border-gray-100">
        <p className="text-sm font-semibold text-gray-900 line-clamp-2 mb-2 leading-snug group-hover:text-gray-700 transition-colors">
          {product.name}
        </p>
        <div className="mb-3">
          <CatalogVariantRow product={product} />
        </div>
        <div className="flex items-center justify-between gap-2">
          <CatalogPrice
            product={product}
            currency={currency}
            className="text-base font-bold"
            style={{ color: "var(--color-primary)" }}
          />
          {product.in_stock ? (
            <CatalogPrimaryAction product={product} />
          ) : (
            <span className="text-xs font-semibold px-2 py-1 text-gray-500 bg-gray-100 rounded">
              Sold out
            </span>
          )}
        </div>
      </div>
    </Link>
  );
}

// ── Fashion: image-first overlay card ────────────────────────────────────────
function CardOverlay({
  product,
  currency,
  locale,
}: {
  product: Product;
  currency: string;
  locale: string;
}) {
  return (
    <Link
      href={`/products/${product.barcode}`}
      className="group relative aspect-[3/4] overflow-hidden bg-gray-100 block rounded-lg card-hover-lift"
    >
      <ProductImage product={product} fill />
      <WishlistButton product={product} />
      <div className="absolute bottom-0 left-0 right-0 p-5 bg-gradient-to-t from-black/75 via-black/40 to-transparent">
        <p
          className="text-xs text-white/70 uppercase tracking-wider mb-1 font-semibold md:opacity-0 md:group-hover:opacity-100 transition-opacity"
          dir={locale?.startsWith("ar") ? "rtl" : undefined}
        >
          {product.category
            ? categoryDisplayName(product.category, locale)
            : null}
        </p>
        <p className="text-base font-bold text-white line-clamp-2 leading-snug mb-2">
          {product.name}
        </p>
        <div className="text-base font-bold text-white mb-2 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
          <CatalogPrice
            product={product}
            currency={currency}
            className="text-base font-bold text-white"
            variant="onDark"
          />
        </div>
        {product.in_stock && (
          <div
            className="md:opacity-0 md:group-hover:opacity-100 transition-opacity"
            onClick={(e) => e.stopPropagation()}
          >
            <CatalogPrimaryAction product={product} tone="onDark" />
          </div>
        )}
      </div>
      {!product.in_stock && (
        <div className="absolute top-4 left-4 bg-black/80 backdrop-blur-sm text-white text-xs font-bold px-3 py-1.5 uppercase tracking-wide rounded-full">
          Sold Out
        </div>
      )}
    </Link>
  );
}

// ── Modern Minimal: clean, no border ─────────────────────────────────────────
function CardMinimal({
  product,
  currency,
  locale,
}: {
  product: Product;
  currency: string;
  locale: string;
}) {
  return (
    <Link href={`/products/${product.barcode}`} className="group flex flex-col">
      <div className="aspect-square bg-gray-50 relative overflow-hidden rounded-lg">
        <ProductImage product={product} />
        <OutOfStockBadge product={product} />
        <WishlistButton product={product} />
      </div>
      <div className="pt-4 pb-1">
        {product.category && (
          <p
            className="text-xs text-gray-500 uppercase tracking-wider mb-1.5 font-semibold"
            dir={locale?.startsWith("ar") ? "rtl" : undefined}
          >
            {categoryDisplayName(product.category, locale)}
          </p>
        )}
        <p className="text-sm font-semibold text-gray-900 line-clamp-2 leading-snug group-hover:text-gray-700 transition-colors mb-2">
          {product.name}
        </p>
        <div className="mb-2">
          <CatalogVariantRow product={product} />
        </div>
        <CatalogPrice
          product={product}
          currency={currency}
          className="text-lg font-bold mb-3"
          style={{ color: "var(--color-primary)" }}
        />
        <CatalogPrimaryAction product={product} />
      </div>
    </Link>
  );
}

// ── Boutique: magazine-style with serif typography ────────────────────────────
function CardMagazine({
  product,
  currency,
  locale,
}: {
  product: Product;
  currency: string;
  locale: string;
}) {
  return (
    <Link
      href={`/products/${product.barcode}`}
      className="group flex flex-col bg-stone-50 overflow-hidden rounded-lg card-hover-lift"
    >
      <div className="aspect-[4/5] relative overflow-hidden bg-stone-100">
        <ProductImage product={product} />
        <OutOfStockBadge product={product} />
        <WishlistButton product={product} />
      </div>
      <div className="p-5">
        {product.category && (
          <p
            className="text-xs uppercase tracking-widest text-stone-500 mb-2 font-semibold"
            dir={locale?.startsWith("ar") ? "rtl" : undefined}
          >
            {categoryDisplayName(product.category, locale)}
          </p>
        )}
        <p className="font-serif text-lg text-stone-900 line-clamp-2 leading-snug mb-3 group-hover:text-stone-700 transition-colors">
          {product.name}
        </p>
        <div className="mb-4">
          <CatalogVariantRow product={product} />
        </div>
        <div className="flex items-center justify-between pt-4 border-t border-stone-200 gap-2">
          <CatalogPrice
            product={product}
            currency={currency}
            className="text-base font-bold"
            style={{ color: "var(--color-primary)" }}
          />
          {product.in_stock ? (
            <CatalogPrimaryAction product={product} />
          ) : (
            <span className="text-xs text-stone-500 font-medium">Sold out</span>
          )}
        </div>
      </div>
    </Link>
  );
}

// ── Shared helpers ────────────────────────────────────────────────────────────
function WishlistButton({ product }: { product: Product }) {
  const { toggle, isWishlisted, setItems } = useWishlistStore();
  const token = useAuthStore((s) => s.token);
  const wishlisted = isWishlisted(product.barcode);
  return (
    <button
      onClick={async (e) => {
        e.preventDefault();
        e.stopPropagation();
        toggle({
          barcode: product.barcode,
          name: product.name,
          price: product.price,
          image_url: product.image_url ?? null,
        });
        if (token) {
          try {
            if (wishlisted) {
              const res = await fetch(
                `/api/storefront-proxy/auth/wishlist/${encodeURIComponent(
                  product.barcode,
                )}`,
                {
                  method: "DELETE",
                  headers: getAuthHeaders() as Record<string, string>,
                },
              );
              const data = await res.json().catch(() => ({}));
              if (data?.items) setItems(data.items);
            } else {
              const res = await fetch("/api/storefront-proxy/auth/wishlist", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  ...getAuthHeaders(),
                },
                body: JSON.stringify({ barcode: product.barcode }),
              });
              const data = await res.json().catch(() => ({}));
              if (data?.items) setItems(data.items);
            }
          } catch {
            const r = await fetch("/api/storefront-proxy/auth/wishlist", {
              headers: getAuthHeaders() as Record<string, string>,
            });
            const d = await r.json().catch(() => ({}));
            if (d?.items) setItems(d.items);
          }
        }
      }}
      className={`absolute top-3 right-3 z-10 w-9 h-9 flex items-center justify-center rounded-full shadow-md transition-all ${
        wishlisted
          ? "bg-white scale-100"
          : "bg-white/90 backdrop-blur-sm hover:bg-white opacity-0 group-hover:opacity-100 hover:scale-110"
      }`}
      aria-label={wishlisted ? "Remove from wishlist" : "Add to wishlist"}
    >
      <svg
        className={`h-4.5 w-4.5 transition-all ${
          wishlisted
            ? "fill-red-500 text-red-500"
            : "fill-none text-gray-600 hover:text-red-500"
        }`}
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={2}
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
        />
      </svg>
    </button>
  );
}

function AddToCartButton({ product }: { product: Product }) {
  const { addItem } = useCartStore();
  const { t } = useLanguage();
  const [added, setAdded] = useState(false);
  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!product.in_stock) return;
    addItem({
      item_id: product.id,
      barcode: product.barcode,
      name: product.name,
      image_url: product.image_url ?? null,
      price: product.price,
      quantity: 1,
      available_qty: product.available_qty,
    });
    setAdded(true);
    setTimeout(() => setAdded(false), 2000);
  };
  return (
    <button
      onClick={handleClick}
      disabled={!product.in_stock}
      className="text-xs font-semibold py-2.5 px-4 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed hover:shadow-md active:scale-95"
      style={{
        backgroundColor: product.in_stock ? "var(--color-primary)" : undefined,
        color: product.in_stock ? "#fff" : undefined,
      }}
    >
      {added ? t.product.addedToCart : t.product.addToCart}
    </button>
  );
}

function ProductImage({
  product,
  fill = true,
}: {
  product: Product;
  fill?: boolean;
}) {
  const imageUrl = resolveMediaUrl(product.image_url);
  if (!imageUrl) {
    return (
      <div className="w-full h-full flex flex-col items-center justify-center gap-3 bg-gradient-to-b from-gray-100 to-gray-50 select-none p-4">
        <div className="w-16 h-16 rounded-2xl bg-white/80 border-2 border-dashed border-gray-200 flex items-center justify-center shadow-inner">
          <svg
            className="w-8 h-8 text-gray-300"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            aria-hidden="true"
          >
            <path
              d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        <span className="text-xs font-medium text-gray-500 text-center">
          No image
        </span>
      </div>
    );
  }
  return (
    <Image
      src={imageUrl}
      alt={product.name}
      fill={fill}
      className="object-cover group-hover:scale-105 transition-transform duration-500"
      sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
    />
  );
}

function OutOfStockBadge({ product }: { product: Product }) {
  if (product.in_stock) return null;
  return (
    <div className="absolute inset-0 bg-white/60 backdrop-blur-sm flex items-center justify-center">
      <span className="bg-white text-gray-700 text-xs font-bold px-4 py-2 rounded-full shadow-md uppercase tracking-wide">
        Out of stock
      </span>
    </div>
  );
}
