import React, { useState } from "react";
import ReactDOM from "react-dom";
import Lightbox from "../common/Lightbox";
import useProductStore from "../../stores/useProductStore";

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 formatDate = (dateStr) => {
  if (!dateStr) return null;
  const normalized = dateStr.endsWith("Z") || dateStr.includes("+") ? dateStr : dateStr + "Z";
  const date = new Date(normalized);
  return date.toLocaleString("fr-FR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const ProductDetailModal = ({ product, onClose }) => {
  const [showLightbox, setShowLightbox] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [editForm, setEditForm] = useState({
    titre: product.titre || "",
    categorie: product.categorie || "",
    type: product.type || "",
    actif: product.actif ?? true,
  });
  const { updateProduct } = useProductStore();

  const handleEditChange = (field, value) => {
    setEditForm((prev) => ({ ...prev, [field]: value }));
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      await updateProduct(product.id, editForm);
      setIsEditing(false);
    } catch (err) {
      console.error("Erreur lors de la sauvegarde:", err);
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancelEdit = () => {
    setEditForm({
      titre: product.titre || "",
      categorie: product.categorie || "",
      type: product.type || "",
      actif: product.actif ?? true,
    });
    setIsEditing(false);
  };

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

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

  // Données étendues (si disponibles depuis le scrape)
  const hasAPropos = product.a_propos && product.a_propos.length > 0;
  const hasDescription = product.description;
  const hasCaracteristiques = product.carateristique && Object.keys(product.carateristique).length > 0;
  const hasDetails = product.details && Object.keys(product.details).length > 0;

  const modalContent = (
    <>
      <div className="modal-backdrop modal-fullscreen" onClick={handleBackdropClick}>
        <div className="modal modal-detail-fullscreen">
          <div className="modal-header">
            <h2>
              <i className="fa-brands fa-amazon"></i> Détail du produit
            </h2>
            <div className="modal-header-actions">
              {!isEditing ? (
                <button className="btn btn-edit" onClick={() => setIsEditing(true)}>
                  <i className="fa-solid fa-pen"></i> Éditer
                </button>
              ) : (
                <>
                  <button className="btn btn-save" onClick={handleSave} disabled={isSaving}>
                    {isSaving ? (
                      <><i className="fa-solid fa-spinner fa-spin"></i> Enregistrement...</>
                    ) : (
                      <><i className="fa-solid fa-check"></i> Enregistrer</>
                    )}
                  </button>
                  <button className="btn btn-cancel" onClick={handleCancelEdit} disabled={isSaving}>
                    <i className="fa-solid fa-times"></i> Annuler
                  </button>
                </>
              )}
              <button className="btn-close" onClick={onClose}>
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
          </div>

          <div className="modal-body">
            {/* Section principale : image + infos essentielles */}
            <div className="detail-main">
              {/* Image */}
              <div
                className={`detail-image-large ${product.url_image ? "clickable" : ""}`}
                onClick={() => product.url_image && setShowLightbox(true)}
              >
                {product.url_image ? (
                  <>
                    <img src={product.url_image} alt={product.titre} />
                    <div className="image-zoom-hint">
                      <i className="fa-solid fa-search-plus"></i> Agrandir
                    </div>
                  </>
                ) : (
                  <div className="no-image">
                    <i className="fa-solid fa-image"></i>
                  </div>
                )}
              </div>

              {/* Infos essentielles */}
              <div className="detail-essential">
                <div className="detail-header-info">
                  <span className="boutique">
                    <i className="fa-brands fa-amazon"></i> {product.boutique}
                  </span>
                  {isEditing ? (
                    <label className="status-toggle">
                      <input
                        type="checkbox"
                        checked={editForm.actif}
                        onChange={(e) => handleEditChange("actif", e.target.checked)}
                      />
                      <span className={`status ${editForm.actif ? "active" : "inactive"}`}>
                        {editForm.actif ? "Actif" : "Inactif"}
                      </span>
                    </label>
                  ) : (
                    product.actif ? (
                      <span className="status active">Actif</span>
                    ) : (
                      <span className="status inactive">Inactif</span>
                    )
                  )}
                </div>

                {isEditing ? (
                  <input
                    type="text"
                    className="edit-input edit-title"
                    value={editForm.titre}
                    onChange={(e) => handleEditChange("titre", e.target.value)}
                    placeholder="Titre du produit"
                  />
                ) : (
                  <h3 className="detail-title-large">{product.titre || "Titre non disponible"}</h3>
                )}

                {/* Badges */}
                {hasBadges && (
                  <div className="detail-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>
                )}

                {/* Prix et Stock côte à côte */}
                <div className="detail-price-stock">
                  {/* Prix */}
                  <div className="detail-section">
                    <h4><i className="fa-solid fa-tag"></i> Prix</h4>
                    <div className="detail-data-list">
                      {product.prix_actuel != null ? (
                        <div className="detail-data-row">
                          <span className="label">Prix actuel</span>
                          <span className="value price-current">{formatPrice(product.prix_actuel)}</span>
                        </div>
                      ) : (
                        <div className="detail-data-empty">Prix non disponible</div>
                      )}
                      {product.prix_conseille != null && (
                        <div className="detail-data-row">
                          <span className="label">Prix conseillé</span>
                          <span className="value strikethrough">{formatPrice(product.prix_conseille)}</span>
                        </div>
                      )}
                      {product.reduction_pourcent != null && product.reduction_pourcent !== 0 && (
                        <div className="detail-data-row">
                          <span className="label">Réduction</span>
                          <span className="value discount">-{product.reduction_pourcent}%</span>
                        </div>
                      )}
                      {product.prix_min_30j != null && (
                        <div className="detail-data-row">
                          <span className="label">Min 30 jours</span>
                          <span className="value">{formatPrice(product.prix_min_30j)}</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Stock & Avis */}
                  <div className="detail-section">
                    <h4><i className="fa-solid fa-box"></i> Stock & Avis</h4>
                    <div className="detail-data-list">
                      {product.etat_stock ? (
                        <div className="detail-data-row">
                          <span className="label">Disponibilité</span>
                          <span className={`value ${product.en_stock ? "in-stock" : "out-of-stock"}`}>
                            {product.etat_stock}
                          </span>
                        </div>
                      ) : (
                        <div className="detail-data-empty">Stock non disponible</div>
                      )}
                      {product.note != null && (
                        <div className="detail-data-row">
                          <span className="label">Note</span>
                          <span className="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)} avis)</span>
                            )}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Métadonnées */}
                <div className="detail-section detail-meta">
                  <h4><i className="fa-solid fa-info-circle"></i> Informations</h4>
                  <div className="detail-data-grid">
                    <div className="detail-data-row">
                      <span className="label">ASIN</span>
                      <span className="value mono">{product.asin}</span>
                    </div>
                    {product.categorie_amazon && (
                      <div className="detail-data-row">
                        <span className="label">Catégorie Amazon</span>
                        <span className="value category-path">{product.categorie_amazon}</span>
                      </div>
                    )}
                    <div className="detail-data-row">
                      <span className="label">Catégorie</span>
                      {isEditing ? (
                        <input
                          type="text"
                          className="edit-input"
                          value={editForm.categorie}
                          onChange={(e) => handleEditChange("categorie", e.target.value)}
                          placeholder="Catégorie personnalisée"
                        />
                      ) : (
                        <span className="value">{product.categorie || "-"}</span>
                      )}
                    </div>
                    <div className="detail-data-row">
                      <span className="label">Type</span>
                      {isEditing ? (
                        <input
                          type="text"
                          className="edit-input"
                          value={editForm.type}
                          onChange={(e) => handleEditChange("type", e.target.value)}
                          placeholder="Type de produit"
                        />
                      ) : (
                        <span className="value">{product.type || "-"}</span>
                      )}
                    </div>
                    {product.cree_le && (
                      <div className="detail-data-row">
                        <span className="label">Ajouté le</span>
                        <span className="value">{formatDate(product.cree_le)}</span>
                      </div>
                    )}
                    {product.dernier_scrape && (
                      <div className="detail-data-row">
                        <span className="label">Dernier scrape</span>
                        <span className="value">{formatDate(product.dernier_scrape)}</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Sections étendues (si disponibles) */}
            <div className="detail-extended">
              {/* À propos */}
              {hasAPropos && (
                <div className="detail-section detail-section-full">
                  <h4><i className="fa-solid fa-list"></i> À propos de cet article</h4>
                  <ul className="detail-bullets">
                    {product.a_propos.map((item, idx) => (
                      <li key={idx}>{item}</li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Description */}
              {hasDescription && (
                <div className="detail-section detail-section-full">
                  <h4><i className="fa-solid fa-align-left"></i> Description</h4>
                  <p className="detail-description">{product.description}</p>
                </div>
              )}

              {/* Caractéristiques techniques */}
              {hasCaracteristiques && (
                <div className="detail-section detail-section-full">
                  <h4><i className="fa-solid fa-microchip"></i> Caractéristiques techniques</h4>
                  <div className="detail-table">
                    {Object.entries(product.carateristique).map(([key, value]) => (
                      <div key={key} className="detail-table-row">
                        <span className="detail-table-key">{key}</span>
                        <span className="detail-table-value">{value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Détails produit */}
              {hasDetails && (
                <div className="detail-section detail-section-full">
                  <h4><i className="fa-solid fa-clipboard-list"></i> Détails du produit</h4>
                  <div className="detail-table">
                    {Object.entries(product.details).map(([key, value]) => (
                      <div key={key} className="detail-table-row">
                        <span className="detail-table-key">{key}</span>
                        <span className="detail-table-value">{value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <div className="modal-actions">
              <a
                href={product.url}
                target="_blank"
                rel="noopener noreferrer"
                className="btn btn-primary"
              >
                <i className="fa-solid fa-external-link"></i> Voir sur Amazon
              </a>
              <button className="btn" onClick={onClose}>
                Fermer
              </button>
            </div>
          </div>
        </div>
      </div>

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

  // Utiliser un portal pour rendre le modal au niveau du body
  return ReactDOM.createPortal(modalContent, document.body);
};

export default ProductDetailModal;
