import React, { useState } from "react";
import useProductStore from "../../stores/useProductStore";
import useConfigStore from "../../stores/useConfigStore";
import PriceChart from "../charts/PriceChart";
import Lightbox from "../common/Lightbox";
import ProductDetailModal from "./ProductDetailModal";

const formatPrice = (price) => {
  if (price == null) return null;
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(price);
};

const formatNumber = (num) => {
  if (num == null) return null;
  return new Intl.NumberFormat("fr-FR").format(num);
};

const ProductCard = ({ product }) => {
  const { scrapeProduct, deleteProduct, scraping } = useProductStore();
  const imageRatio = useConfigStore((state) => state.config.ui?.image_ratio || 40);
  const isScraping = scraping[product.id];
  const [showLightbox, setShowLightbox] = useState(false);
  const [showDetail, setShowDetail] = useState(false);

  const handleScrape = async () => {
    try {
      await scrapeProduct(product.id);
    } catch (err) {
      console.error("Erreur scraping:", err);
    }
  };

  const handleDelete = async () => {
    if (!confirm(`Supprimer "${product.titre || product.asin}" ?`)) return;
    try {
      await deleteProduct(product.id);
    } catch (err) {
      console.error("Erreur suppression:", err);
    }
  };

  const hasBadges =
    product.prime ||
    product.choix_amazon ||
    product.offre_limitee ||
    product.exclusivite_amazon;

  return (
    <article className="product-card">
      <div className="product-header">
        <span className="boutique">
          <i className="fa-brands fa-amazon"></i> {product.boutique}
        </span>
        <div className="header-right">
          <a
            href={product.url}
            target="_blank"
            rel="noopener noreferrer"
            className="header-link"
            title="Voir sur Amazon"
          >
            <i className="fa-solid fa-external-link"></i>
          </a>
          {product.actif ? (
            <span className="status active">Actif</span>
          ) : (
            <span className="status inactive">Inactif</span>
          )}
        </div>
      </div>

      <h3
        className="product-title clickable"
        title={product.titre}
        onClick={() => setShowDetail(true)}
      >
        {product.titre || "Titre non disponible"}
      </h3>

      <div className="product-body" style={{ "--image-ratio": imageRatio }}>
        <div
          className={`product-image ${product.url_image ? "clickable" : ""}`}
          onClick={() => product.url_image && setShowLightbox(true)}
        >
          {product.url_image ? (
            <>
              <img src={product.url_image} alt={product.titre} loading="lazy" />
              <div className="image-zoom-hint">
                <i className="fa-solid fa-search-plus"></i>
              </div>
            </>
          ) : (
            <div className="no-image">
              <i className="fa-solid fa-image"></i>
            </div>
          )}
        </div>

        <div className="product-info">
          {/* Section Prix */}
          <div className="price-section">
            {product.prix_actuel != null && (
              <div className="price-row price-current">
                <span className="price-label">Actuel</span>
                <span className="price-value">{formatPrice(product.prix_actuel)}</span>
              </div>
            )}
            {product.prix_conseille != null && (
              <div className="price-row price-list">
                <span className="price-label">Prix conseillé</span>
                <span className="price-value strikethrough">
                  {formatPrice(product.prix_conseille)}
                </span>
              </div>
            )}
            {product.reduction_pourcent != null && product.reduction_pourcent !== 0 && (
              <div className="price-row price-discount">
                <span className="price-label">Réduction</span>
                <span className="price-value discount">-{product.reduction_pourcent}%</span>
              </div>
            )}
            {product.prix_min_30j != null && (
              <div className="price-row price-min">
                <span className="price-label">Min 30j</span>
                <span className="price-value">{formatPrice(product.prix_min_30j)}</span>
              </div>
            )}
          </div>

          {/* Stock et Note */}
          <div className="product-stats">
            {product.etat_stock && (
              <div className="stat-row">
                <span className="stat-label">Stock</span>
                <span className={`stat-value ${product.en_stock ? "in-stock" : "out-of-stock"}`}>
                  {product.etat_stock}
                </span>
              </div>
            )}
            {product.note != null && (
              <div className="stat-row">
                <span className="stat-label">Note</span>
                <span className="stat-value rating">
                  <i className="fa-solid fa-star"></i> {product.note.toFixed(1)}
                  {product.nombre_avis != null && (
                    <span className="review-count">({formatNumber(product.nombre_avis)})</span>
                  )}
                </span>
              </div>
            )}
          </div>

          {/* Badges */}
          {hasBadges && (
            <div className="product-badges">
              {product.choix_amazon && (
                <span className="badge badge-choice">
                  <i className="fa-solid fa-check-circle"></i> Choix Amazon
                </span>
              )}
              {product.prime && (
                <span className="badge badge-prime">
                  <i className="fa-solid fa-truck-fast"></i> Prime
                </span>
              )}
              {product.offre_limitee && (
                <span className="badge badge-deal">
                  <i className="fa-solid fa-bolt"></i> Offre limitée
                </span>
              )}
              {product.exclusivite_amazon && (
                <span className="badge badge-exclusive">
                  <i className="fa-solid fa-gem"></i> Exclusivité
                </span>
              )}
            </div>
          )}

          {/* Méta */}
          <div className="product-meta">
            <span className="asin">Ref: {product.asin}</span>
            {product.categorie_amazon && (
              <span className="category" title={product.categorie_amazon}>
                <i className="fa-solid fa-folder-tree"></i> {product.categorie_amazon.split(" > ").slice(-1)[0]}
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Graphique historique */}
      <PriceChart
        productId={product.id}
        prixConseille={product.prix_conseille}
        prixMin30j={product.prix_min_30j}
      />

      <div className="product-actions">
        <button
          className="btn btn-scrape"
          onClick={handleScrape}
          disabled={isScraping}
        >
          {isScraping ? (
            <>
              <i className="fa-solid fa-spinner fa-spin"></i> Scraping...
            </>
          ) : (
            <>
              <i className="fa-solid fa-download"></i> Scraper
            </>
          )}
        </button>
        <button className="btn btn-detail" onClick={() => setShowDetail(true)}>
          <i className="fa-solid fa-expand"></i>
        </button>
        <button className="btn btn-delete" onClick={handleDelete}>
          <i className="fa-solid fa-trash"></i>
        </button>
      </div>

      {showDetail && (
        <ProductDetailModal
          product={product}
          onClose={() => setShowDetail(false)}
        />
      )}

      {showLightbox && product.url_image && (
        <Lightbox
          imageUrl={product.url_image}
          alt={product.titre}
          onClose={() => setShowLightbox(false)}
        />
      )}
    </article>
  );
};

export default ProductCard;
