import React, { useState } from "react";
import useProductStore from "../../stores/useProductStore";
import * as api from "../../api/client";

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

const AddProductModal = ({ onClose }) => {
  const { addProduct } = useProductStore();
  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [preview, setPreview] = useState(null);

  // Extrait l'ASIN d'une URL Amazon
  const extractAsin = (amazonUrl) => {
    const patterns = [
      /\/dp\/([A-Z0-9]{10})/i,
      /\/gp\/product\/([A-Z0-9]{10})/i,
      /\/ASIN\/([A-Z0-9]{10})/i,
      /\?asin=([A-Z0-9]{10})/i,
    ];

    for (const pattern of patterns) {
      const match = amazonUrl.match(pattern);
      if (match) return match[1].toUpperCase();
    }
    return null;
  };

  // Étape 1 : Scraper pour prévisualisation
  const handlePreview = async (e) => {
    e.preventDefault();
    setError(null);

    // Validation URL Amazon
    if (!url.includes("amazon.fr")) {
      setError("L'URL doit être une URL Amazon.fr");
      return;
    }

    const asin = extractAsin(url);
    if (!asin) {
      setError("Impossible d'extraire l'ASIN de cette URL");
      return;
    }

    const canonicalUrl = `https://www.amazon.fr/dp/${asin}`;

    setLoading(true);
    try {
      // Appeler l'API de prévisualisation
      const result = await api.scrapePreview(canonicalUrl);
      setPreview({
        asin,
        url: canonicalUrl,
        urlOriginal: url,
        data: result.data,
      });
    } catch (err) {
      setError(err.message || "Erreur lors du scraping");
    } finally {
      setLoading(false);
    }
  };

  // Étape 2 : Confirmer et enregistrer
  const handleConfirm = async () => {
    if (!preview) return;

    const data = preview.data;
    setSaving(true);
    setError(null);
    try {
      await addProduct({
        // Données produit
        boutique: "amazon",
        url: preview.url,
        asin: preview.asin,
        titre: data.titre || null,
        url_image: data.url_image_principale || null,
        categorie: null,
        type: null,
        actif: true,
        // Données snapshot (depuis preview)
        prix_actuel: data.prix_actuel ?? null,
        prix_conseille: data.prix_conseille ?? null,
        prix_min_30j: data.prix_min_30j ?? null,
        etat_stock: data.etat_stock ?? null,
        en_stock: data.en_stock ?? null,
        note: data.note ?? null,
        nombre_avis: data.nombre_avis ?? null,
        prime: data.prime ?? null,
        choix_amazon: data.choix_amazon ?? null,
        offre_limitee: data.offre_limitee ?? null,
        exclusivite_amazon: data.exclusivite_amazon ?? null,
        // Données étendues
        a_propos: data.a_propos ?? null,
        description: data.description ?? null,
        carateristique: data.carateristique ?? null,
        details: data.details ?? null,
      });

      onClose();
    } catch (err) {
      setError(err.message);
      setSaving(false);
    }
  };

  // Retour à l'étape saisie
  const handleBack = () => {
    setPreview(null);
    setError(null);
  };

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget && !loading && !saving) {
      onClose();
    }
  };

  // Étape prévisualisation complète
  if (preview) {
    const data = preview.data;
    const hasBadges = data.prime || data.choix_amazon || data.offre_limitee || data.exclusivite_amazon;

    return (
      <div className="modal-backdrop" onClick={handleBackdropClick}>
        <div className="modal modal-large">
          <div className="modal-header">
            <h2>Confirmer l'ajout</h2>
            <button className="btn-close" onClick={onClose} disabled={saving}>
              <i className="fa-solid fa-times"></i>
            </button>
          </div>

          <div className="modal-body">
            {error && <div className="form-error">{error}</div>}

            <div className="preview-product">
              {/* Header avec image et infos principales */}
              <div className="preview-main">
                <div className="preview-image">
                  {data.url_image_principale ? (
                    <img src={data.url_image_principale} alt={data.titre} />
                  ) : (
                    <div className="no-image">
                      <i className="fa-solid fa-image"></i>
                    </div>
                  )}
                </div>

                <div className="preview-details">
                  <h3 className="preview-title">{data.titre || "Titre non disponible"}</h3>

                  <div className="preview-meta">
                    <span className="preview-asin">ASIN: {preview.asin}</span>
                    <a
                      href={preview.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="preview-link"
                    >
                      <i className="fa-solid fa-external-link"></i> Voir sur Amazon
                    </a>
                  </div>

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

              {/* Section prix et stock */}
              <div className="preview-grid">
                <div className="preview-section">
                  <h4>Prix</h4>
                  <div className="preview-data-list">
                    {data.prix_actuel != null && (
                      <div className="preview-data-row">
                        <span className="label">Prix actuel</span>
                        <span className="value price-current">{formatPrice(data.prix_actuel)}</span>
                      </div>
                    )}
                    {data.prix_conseille != null && (
                      <div className="preview-data-row">
                        <span className="label">Prix conseillé</span>
                        <span className="value strikethrough">{formatPrice(data.prix_conseille)}</span>
                      </div>
                    )}
                    {data.reduction_pourcent != null && data.reduction_pourcent !== 0 && (
                      <div className="preview-data-row">
                        <span className="label">Réduction</span>
                        <span className="value discount">-{data.reduction_pourcent}%</span>
                      </div>
                    )}
                    {data.prix_min_30j != null && (
                      <div className="preview-data-row">
                        <span className="label">Min 30 jours</span>
                        <span className="value">{formatPrice(data.prix_min_30j)}</span>
                      </div>
                    )}
                    {data.prix_actuel == null && (
                      <div className="preview-data-empty">Prix non disponible</div>
                    )}
                  </div>
                </div>

                <div className="preview-section">
                  <h4>Stock & Avis</h4>
                  <div className="preview-data-list">
                    {data.etat_stock && (
                      <div className="preview-data-row">
                        <span className="label">Disponibilité</span>
                        <span className={`value ${data.en_stock ? "in-stock" : "out-of-stock"}`}>
                          {data.etat_stock}
                        </span>
                      </div>
                    )}
                    {data.note != null && (
                      <div className="preview-data-row">
                        <span className="label">Note</span>
                        <span className="value rating">
                          <i className="fa-solid fa-star"></i> {data.note.toFixed(1)}
                          {data.nombre_avis != null && (
                            <span className="review-count"> ({data.nombre_avis.toLocaleString("fr-FR")} avis)</span>
                          )}
                        </span>
                      </div>
                    )}
                    {!data.etat_stock && data.note == null && (
                      <div className="preview-data-empty">Informations non disponibles</div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <p className="preview-info">
              <i className="fa-solid fa-info-circle"></i>
              Ces informations seront enregistrées et mises à jour automatiquement lors des prochains scrapings.
            </p>

            <div className="modal-actions">
              <button type="button" className="btn" onClick={handleBack} disabled={saving}>
                <i className="fa-solid fa-arrow-left"></i> Modifier l'URL
              </button>
              <button
                type="button"
                className="btn btn-primary"
                onClick={handleConfirm}
                disabled={saving}
              >
                {saving ? (
                  <>
                    <i className="fa-solid fa-spinner fa-spin"></i> Enregistrement...
                  </>
                ) : (
                  <>
                    <i className="fa-solid fa-check"></i> Confirmer et ajouter
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Étape saisie URL
  return (
    <div className="modal-backdrop" onClick={handleBackdropClick}>
      <div className="modal">
        <div className="modal-header">
          <h2>Ajouter un produit</h2>
          <button className="btn-close" onClick={onClose} disabled={loading}>
            <i className="fa-solid fa-times"></i>
          </button>
        </div>

        <form onSubmit={handlePreview} className="modal-body">
          {error && <div className="form-error">{error}</div>}

          <div className="form-group">
            <label htmlFor="url">URL Amazon.fr</label>
            <input
              type="url"
              id="url"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="https://www.amazon.fr/dp/B0..."
              required
              autoFocus
              disabled={loading}
            />
            <p className="form-hint">
              Collez l'URL complète du produit Amazon.fr
            </p>
          </div>

          <div className="modal-actions">
            <button type="button" className="btn" onClick={onClose} disabled={loading}>
              Annuler
            </button>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              {loading ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin"></i> Chargement...
                </>
              ) : (
                <>
                  <i className="fa-solid fa-eye"></i> Prévisualiser
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddProductModal;
