'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Product } from '@/types/woocommerce';
import { siteConfig } from '@/config/site';
import { useCart } from '@/context/CartContext';
import { ProductHoverTagsSettings } from '@/lib/settings';

interface ProductCardProps {
  product: Product;
  badgeText?: string;
  hideBadge?: boolean;
  isNew?: boolean;
  /** Top-selling variant: wraps the card in .tcard (horizontal layout per design) */
  featured?: boolean;
  /** Kept for caller compatibility */
  index?: number;
  /** Kept for caller compatibility */
  hoverTags?: ProductHoverTagsSettings;
}

const BDT = (n: number) => '৳' + Math.round(n || 0).toLocaleString('en-US');

function BagIcon() {
  return (
    <svg className="ic" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M6 7h12l-1 13H7L6 7z" />
      <path d="M9 7a3 3 0 0 1 6 0" />
    </svg>
  );
}

export default function ProductCard({
  product,
  badgeText,
  hideBadge = false,
  isNew = false,
  featured = false,
}: ProductCardProps) {
  const { addToCart, quickAdd } = useCart();
  const router = useRouter();

  const isOutOfStock = product.stockStatus === 'OUT_OF_STOCK';
  const isLowStock = product.stockStatus === 'ON_BACKORDER';

  // Price range (variable products with differing variation prices)
  const hasRange =
    product.minPrice !== undefined &&
    product.maxPrice !== undefined &&
    product.minPrice < product.maxPrice;

  const price = hasRange ? product.minPrice! : product.price || 0;
  const wasPrice = hasRange
    ? product.minRegularPrice || product.regularPrice || 0
    : product.regularPrice || 0;

  const discountPercent =
    product.discountPercent ||
    (wasPrice > price && wasPrice > 0
      ? Math.round(((wasPrice - price) / wasPrice) * 100)
      : 0);

  // Variant labels → "250g · 500g" (from variations, fallback to available sizes)
  const variantLabels: string[] = [];
  if (product.variations && product.variations.length > 0) {
    for (const v of product.variations) {
      const attrLabel = (v.attributes || [])
        .map((a) => String(a.option || '').trim())
        .filter(Boolean)
        .join(' ');
      const label = attrLabel || String(v.name || '').trim();
      if (label && !variantLabels.includes(label)) variantLabels.push(label);
    }
  }
  if (variantLabels.length === 0 && product.availableSizes && product.availableSizes.length > 0) {
    for (const s of product.availableSizes) {
      const label = String(s).trim();
      if (label && !variantLabels.includes(label)) variantLabels.push(label);
    }
  }

  // Badge priority: custom text > Best Selling > New > Few left
  const customBadge = typeof badgeText === 'string' ? badgeText.trim() : '';
  const mainBadge = customBadge
    ? customBadge
    : featured
    ? 'Best Selling'
    : isNew
    ? 'New'
    : isLowStock
    ? 'Few left'
    : null;

  const badgeClass =
    mainBadge === 'Best Selling'
      ? 'ptag bs'
      : mainBadge === 'New'
      ? 'ptag nw'
      : mainBadge === 'Few left'
      ? 'ptag low'
      : 'ptag';

  const handleAdd = () => {
    // Use quickAdd so variable products open the variation picker in the cart sidebar
    quickAdd(product, false);
  };

  const handleBuyNow = () => {
    quickAdd(product, true);
  };

  const productUrl = `/product/${product.slug}`;
  const notifyUrl = `https://wa.me/${
    siteConfig.contact.whatsappNumber
  }?text=${encodeURIComponent(`Restock হলে জানাবেন: ${product.name}`)}`;

  const card = (
    <article className="item">
      <Link className="frame" href={productUrl} aria-label={product.name}>
        {!hideBadge && (
          <span className="ptags">
            {mainBadge ? <span className={badgeClass}>{mainBadge}</span> : <span></span>}
            {discountPercent > 0 && <span className="ptag off">-{discountPercent}%</span>}
          </span>
        )}
        {isOutOfStock && <span className="oos">Sold out</span>}
        <img
          src={product.image || '/images/placeholder.png'}
          alt={product.name}
          loading="lazy"
          width={400}
          height={400}
          onError={(e) => {
            (e.currentTarget as HTMLImageElement).src = '/images/placeholder.png';
          }}
        />
      </Link>
      <div className="ibody">
        <Link className="iname" href={productUrl}>
          {product.name}
        </Link>
        {product.brand ? <span className="ien">{product.brand}</span> : null}
        <p className="meta">
          {hasRange && <span className="from">from</span>}
          <b>{BDT(price)}</b>
          {wasPrice > price && <s>{BDT(wasPrice)}</s>}
        </p>
        {variantLabels.length > 0 && <p className="runs">{variantLabels.join(' · ')}</p>}
        <div className="cbtns">
          {isOutOfStock ? (
            <a className="btn btn-ghost one" href={notifyUrl} target="_blank" rel="noopener">
              Notify me
            </a>
          ) : (
            <>
              <button
                type="button"
                className="btn btn-ghost"
                onClick={handleAdd}
                aria-label={`Add ${product.name} to cart`}
              >
                <BagIcon />
                <span>Add</span>
              </button>
              <button
                type="button"
                className="btn btn-pri"
                onClick={handleBuyNow}
                aria-label={`Buy ${product.name} now`}
              >
                Buy now
              </button>
            </>
          )}
        </div>
      </div>
    </article>
  );

  return featured ? <div className="tcard">{card}</div> : card;
}
