/**
 * Oveyo PWA V8.1 — Composant PhotoForm
 * =======================================
 *
 * Flow utilisateur :
 *   Étape 1 : choix type photo (ticket / rayon / flyer) + enseigne (optionnel)
 *   Étape 2 : upload (input file ou camera native)
 *   Étape 3 : spinner "Analyse en cours…" (5-15 sec côté Claude Vision)
 *   Étape 4 : affichage des prix extraits avec checkbox + édition
 *   Étape 5 : confirmation → propositions créées (status pending)
 *
 * Quota : 5 photos/jour/user (vérifié côté serveur)
 */

const PhotoForm = ({ state, setState, setActiveTab, onLoginRequired, onBack, category }) => {
  const { ArrowLeft, Camera, Upload, Loader2, Check, X, Edit3, AlertCircle } = window.LucideReact || {};
  const flash = window.OveyoUI?.useFlash ? window.OveyoUI.useFlash() : { show: () => {} };

  const SAFE_TOP = { paddingTop: 'calc(env(safe-area-inset-top, 0px) + 16px)' };

  const [step, setStep] = React.useState('type');     // type → upload → parsing → review → done
  const [photoType, setPhotoType] = React.useState('ticket');
  const [selectedBrand, setSelectedBrand] = React.useState(null);
  const [brands, setBrands] = React.useState([]);
  // V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : sélection de branche après enseigne + result du parse
  const [selectedBranch, setSelectedBranch] = React.useState(null);
  const [branches, setBranches] = React.useState([]);
  const [parseResult, setParseResult] = React.useState(null);
  // V8.6.5-PHOTO-BRANDS-FIX V8.6.5 : champ libre pour enseigne hors-liste
  const [brandFreeText, setBrandFreeText] = React.useState('');
  const [useFreeText, setUseFreeText] = React.useState(false);
  const [quota, setQuota] = React.useState(null);
  const [photoFile, setPhotoFile] = React.useState(null);
  const [photoPreview, setPhotoPreview] = React.useState(null);
  const [photoId, setPhotoId] = React.useState(null);
  const [extractedItems, setExtractedItems] = React.useState([]);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const isLoggedIn = !!state.user?.session_token;
  const fileInputRef = React.useRef(null);

  // Charger quota + enseignes au montage
  React.useEffect(() => {
    if (!isLoggedIn) return;
    fetch('/api/pwa/photo/quota', {
      headers: { 'Authorization': 'Bearer ' + state.user.session_token },
    }).then((r) => r.json()).then(setQuota).catch(() => {});

    // V8.6.5-PHOTO-BRANDS-FIX V8.6.5 : fetch les enseignes ET stations séparément
    // (le backend ne renvoie category_slug que si on filtre par catégorie)
    Promise.all([
      fetch('/api/pwa/brands?category=enseigne').then((r) => r.json()).catch(() => ({})),
      fetch('/api/pwa/brands?category=station').then((r) => r.json()).catch(() => ({})),
    ]).then(([enseignes, stations]) => {
      const all = [...(enseignes.brands || []), ...(stations.brands || [])];
      setBrands(all);
    });
  }, [isLoggedIn]);

  // V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : refresh branches quand enseigne change
  React.useEffect(() => {
    if (!selectedBrand?.id) {
      setBranches([]);
      setSelectedBranch(null);
      return;
    }
    fetch(`/api/pwa/branches?brand_id=${selectedBrand.id}`)
      .then((r) => r.json())
      .then((d) => setBranches(d.branches || []))
      .catch(() => setBranches([]));
    setSelectedBranch(null); // reset si enseigne change
  }, [selectedBrand?.id]);

  const onFileChosen = (file) => {
    if (!file) return;
    if (file.size > 8 * 1024 * 1024) {
      flash.show('error', 'Photo trop volumineuse (max 8 MB)');
      return;
    }
    setPhotoFile(file);
    const reader = new FileReader();
    reader.onload = (e) => setPhotoPreview(e.target.result);
    reader.readAsDataURL(file);
    setStep('upload');
  };

  const submitPhoto = async () => {
    if (!photoFile || !isLoggedIn) {
      if (!isLoggedIn) onLoginRequired?.();
      return;
    }
    setStep('parsing');
    setError(null);

    try {
      const fd = new FormData();
      fd.append('photo', photoFile);
      const url = new URL('/api/pwa/photo/parse-prices', window.location.origin);
      url.searchParams.set('photo_type', photoType);
      if (selectedBrand?.id) url.searchParams.set('brand_id', selectedBrand.id);
      // V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : si branche sélectionnée, l'envoyer
      if (selectedBranch?.id) url.searchParams.set('branch_id', selectedBranch.id);
      // V8.6.5-PHOTO-BRANDS-FIX V8.6.5 : si l'user a saisi un nom libre, le passer
      if (useFreeText && brandFreeText.trim()) {
        url.searchParams.set('brand_name_freetext', brandFreeText.trim());
      }

      const r = await fetch(url.toString(), {
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + state.user.session_token },
        body: fd,
      });

      if (r.status === 429) {
        const d = await r.json().catch(() => ({}));
        setError(d.detail || 'Limite quotidienne atteinte');
        setStep('upload');
        return;
      }

      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        setError(d.detail || 'Erreur d\'analyse');
        setStep('upload');
        return;
      }

      const data = await r.json();
      setPhotoId(data.photo_id);
      // V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : stocker le résultat complet (pour matched_branch_id)
      setParseResult(data);

      // Préparer les items pour édition
      const items = (data.items || []).map((it, idx) => ({
        ...it,
        idx,
        selected: true,        // tout coché par défaut
        editing: false,        // pas en mode édition
      }));
      setExtractedItems(items);

      if (items.length === 0) {
        setError('Aucun prix détecté sur cette photo. Essaie avec une photo plus nette.');
        setStep('upload');
        return;
      }

      setStep('review');
    } catch (e) {
      setError('Erreur réseau');
      setStep('upload');
    }
  };

  const toggleItem = (idx) => {
    setExtractedItems((prev) =>
      prev.map((it) => it.idx === idx ? { ...it, selected: !it.selected } : it)
    );
  };

  const updateItemPrice = (idx, newPrice) => {
    const p = parseInt(newPrice, 10);
    if (isNaN(p) || p < 1) return;
    setExtractedItems((prev) =>
      prev.map((it) => it.idx === idx ? { ...it, price: p } : it)
    );
  };

  const confirmProposals = async () => {
    if (!photoId) return;
    setSubmitting(true);
    try {
      const r = await fetch(`/api/pwa/photo/${photoId}/confirm`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + state.user.session_token,
        },
        body: JSON.stringify({
          items: extractedItems.map((it) => ({
            name_raw: it.name_raw,
            price: it.price,
            matched_product_id: it.matched_product_id,
            quantity: it.quantity,
            confidence: it.confidence,
            selected: it.selected,
          })),
          brand_id: selectedBrand?.id || null,
          // V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : envoie branch_id (sélectionné OU auto-détecté côté serveur)
          branch_id: selectedBranch?.id || (parseResult?.matched_branch_id) || null,
        }),
      });
      const d = await r.json();
      if (d.ok) {
        setStep('done');
        flash.show('success', `✅ ${d.created_proposals} prix envoyés à validation`);
      } else {
        flash.show('error', 'Erreur lors de la confirmation');
      }
    } catch (e) {
      flash.show('error', 'Erreur réseau');
    } finally {
      setSubmitting(false);
    }
  };

  // ========================================================
  // RENDER
  // ========================================================
  if (!isLoggedIn) {
    return (
      <div className="px-5 pb-28" style={SAFE_TOP}>
        <button onClick={onBack} className="flex items-center gap-1.5 text-sm font-bold text-slate mb-4">
          <ArrowLeft size={18} /> Retour
        </button>
        <div className="bg-white rounded-2xl p-6 text-center" style={{ border: '1px solid #EAEEF4' }}>
          <Camera size={32} className="mx-auto mb-3" style={{ color: '#9AA5B5' }} />
          <p className="text-sm text-slate mb-4">Connecte-toi pour partager une photo de prix</p>
          <button
            onClick={onLoginRequired}
            className="px-5 py-2.5 rounded-xl font-bold text-white"
            style={{ background: '#102A43' }}
          >
            Se connecter
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="px-5 pb-28" style={SAFE_TOP}>
      <button
        onClick={() => {
          if (step === 'review') setStep('upload');
          else if (step === 'upload') setStep('type');
          else onBack();
        }}
        className="flex items-center gap-1.5 text-sm font-bold text-slate mb-4"
      >
        <ArrowLeft size={18} /> Retour
      </button>

      <div className="flex items-center gap-3 mb-4">
        <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#9333EA' }}>
          <Camera size={20} strokeWidth={2.2} className="text-white" />
        </div>
        <div className="flex-1 min-w-0">
          <h1 className="font-display font-bold text-lg text-ink leading-tight">Photographier des prix</h1>
          <p className="text-[11px] text-slate mt-0.5">
            {step === 'type' && 'Étape 1/3 · Type'}
            {step === 'upload' && 'Étape 2/3 · Upload'}
            {step === 'parsing' && 'Analyse en cours…'}
            {step === 'review' && 'Étape 3/3 · Vérification'}
            {step === 'done' && 'Terminé !'}
          </p>
        </div>
      </div>

      {/* Quota indicator */}
      {quota && step !== 'done' && (
        <div className="rounded-xl p-3 mb-3 text-xs flex items-center gap-2" style={{
          background: quota.remaining === 0 ? '#FEF3F2' : '#F8FAFC',
          border: '1px solid ' + (quota.remaining === 0 ? '#FECACA' : '#EAEEF4'),
        }}>
          <AlertCircle size={14} style={{ color: quota.remaining === 0 ? '#B91C1C' : '#5B6B7E' }} />
          <span className={quota.remaining === 0 ? 'text-orange font-bold' : 'text-slate'}>
            {quota.remaining > 0
              ? `${quota.remaining}/${quota.limit} photos restantes aujourd'hui`
              : 'Limite quotidienne atteinte. Réessaie demain.'}
          </span>
        </div>
      )}

      {/* === Étape 1 : Type de photo === */}
      {step === 'type' && (
        <div className="space-y-3">
          <h2 className="font-bold text-sm text-ink mb-1">Type de photo</h2>
          {[
            { slug: 'ticket', label: 'Ticket de caisse', icon: '🧾', desc: 'Auchan, Carrefour…' },
            { slug: 'shelf',  label: 'Étiquette de rayon', icon: '🏷️', desc: 'Photo prise en magasin' },
            { slug: 'flyer',  label: 'Flyer / Catalogue', icon: '📄', desc: 'Promotions papier' },
          ].map((t) => (
            <button
              key={t.slug}
              onClick={() => setPhotoType(t.slug)}
              className="w-full bg-white rounded-xl p-3 flex items-center gap-3 text-left transition-all"
              style={{
                border: '1px solid ' + (photoType === t.slug ? '#9333EA' : '#EAEEF4'),
                background: photoType === t.slug ? '#FAF5FF' : 'white',
              }}
            >
              <div className="w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0" style={{ background: '#F1F4F9' }}>
                {t.icon}
              </div>
              <div className="flex-1 min-w-0">
                <div className="font-bold text-sm text-ink">{t.label}</div>
                <div className="text-[11px] text-slate">{t.desc}</div>
              </div>
              {photoType === t.slug && <Check size={18} style={{ color: '#9333EA' }} />}
            </button>
          ))}

          <h2 className="font-bold text-sm text-ink mt-5 mb-1">Enseigne (optionnel)</h2>
          {/* V8.6.5-PHOTO-BRANDS-FIX V8.6.5 : dropdown + option "Autre" qui ouvre un champ libre */}
          <select
            value={useFreeText ? '__free__' : (selectedBrand?.id || '')}
            onChange={(e) => {
              const v = e.target.value;
              if (v === '__free__') {
                setUseFreeText(true);
                setSelectedBrand(null);
              } else {
                setUseFreeText(false);
                setBrandFreeText('');
                const id = parseInt(v);
                setSelectedBrand(brands.find((b) => b.id === id) || null);
              }
            }}
            className="w-full px-3 py-2.5 rounded-xl text-sm outline-none bg-white"
            style={{ border: '1px solid #EAEEF4' }}
          >
            <option value="">— Pas précisé —</option>
            {brands.map((b) => (
              <option key={b.id} value={b.id}>{b.name}</option>
            ))}
            <option value="__free__">🆕 Autre enseigne (saisir)</option>
          </select>
          {useFreeText && (
            <input
              type="text"
              value={brandFreeText}
              onChange={(e) => setBrandFreeText(e.target.value)}
              placeholder="Ex : Lebon, Auchan Almadies, Petit Marché..."
              className="w-full mt-2 px-3 py-2.5 rounded-xl text-sm outline-none bg-white"
              style={{ border: '1px solid #EAEEF4' }}
            />
          )}

          {/* V8.6.3-PHOTO-BRANCH-SELECT V8.6.3 : sélecteur de branche/succursale */}
          {selectedBrand && branches.length > 0 && (
            <>
              <h2 className="font-bold text-sm text-ink mt-4 mb-1">Succursale (optionnel)</h2>
              <select
                value={selectedBranch?.id || ''}
                onChange={(e) => {
                  const id = parseInt(e.target.value);
                  setSelectedBranch(branches.find((b) => b.id === id) || null);
                }}
                className="w-full px-3 py-2.5 rounded-xl text-sm outline-none bg-white"
                style={{ border: '1px solid #EAEEF4' }}
              >
                <option value="">— Auto-détecter (depuis le ticket) —</option>
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>{b.name}</option>
                ))}
              </select>
              <p className="text-[11px] text-slate mt-1">
                Si tu laisses vide, on essaiera de la trouver à partir de l'adresse sur le ticket.
              </p>
            </>
          )}

          <button
            onClick={() => setStep('upload')}
            className="w-full mt-4 px-5 py-3.5 rounded-2xl font-bold text-white"
            style={{ background: '#102A43' }}
          >
            Continuer
          </button>
        </div>
      )}

      {/* === Étape 2 : Upload === */}
      {step === 'upload' && (
        <div className="space-y-3">
          <input
            ref={fileInputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            capture="environment"
            onChange={(e) => onFileChosen(e.target.files[0])}
            style={{ display: 'none' }}
          />

          {photoPreview ? (
            <div className="bg-white rounded-2xl p-3" style={{ border: '1px solid #EAEEF4' }}>
              <img src={photoPreview} alt="Aperçu" style={{ width: '100%', maxHeight: 320, objectFit: 'contain', borderRadius: 12 }} />
              <div className="flex gap-2 mt-3">
                <button
                  onClick={() => fileInputRef.current?.click()}
                  className="flex-1 px-3 py-2 rounded-lg text-sm font-bold"
                  style={{ background: '#F1F4F9', color: '#5B6B7E' }}
                >
                  Changer
                </button>
                <button
                  onClick={submitPhoto}
                  disabled={!quota?.allowed}
                  className="flex-1 px-3 py-2 rounded-lg text-sm font-bold text-white"
                  style={{ background: quota?.allowed ? '#9333EA' : '#DDE3EC' }}
                >
                  Analyser ✨
                </button>
              </div>
            </div>
          ) : (
            <button
              onClick={() => fileInputRef.current?.click()}
              className="w-full bg-white rounded-2xl p-8 flex flex-col items-center gap-3 active:opacity-70"
              style={{ border: '2px dashed #C4B5FD' }}
              disabled={!quota?.allowed}
            >
              <Upload size={32} style={{ color: '#9333EA' }} />
              <div className="font-bold text-sm text-ink">Choisir ou prendre une photo</div>
              <div className="text-[11px] text-slate text-center">JPG, PNG ou WebP · max 8 MB</div>
            </button>
          )}

          {error && (
            <div className="rounded-xl p-3 text-xs" style={{ background: '#FEF3F2', color: '#B91C1C', border: '1px solid #FECACA' }}>
              {error}
            </div>
          )}
        </div>
      )}

      {/* === Étape 3 : Parsing en cours === */}
      {step === 'parsing' && (
        <div className="bg-white rounded-2xl p-8 text-center" style={{ border: '1px solid #EAEEF4' }}>
          <Loader2 size={36} className="mx-auto mb-3 animate-spin" style={{ color: '#9333EA' }} />
          <div className="font-bold text-sm text-ink mb-1">Analyse de la photo…</div>
          <div className="text-xs text-slate leading-snug">
            Claude IA extrait tous les prix de ta photo.<br />
            Cela prend 5 à 15 secondes.
          </div>
          {photoPreview && (
            <img src={photoPreview} alt="" style={{ maxHeight: 120, marginTop: 16, borderRadius: 8, opacity: 0.6 }} />
          )}
        </div>
      )}

      {/* === Étape 4 : Vérification des prix extraits === */}
      {step === 'review' && (
        <div className="space-y-3">
          <div className="rounded-xl p-3" style={{ background: '#ECFDF5', border: '1px solid #A7F3D0' }}>
            <div className="text-xs font-bold" style={{ color: '#15803D' }}>
              ✨ {extractedItems.length} prix détectés
            </div>
            <div className="text-[11px] text-slate mt-0.5">
              Décoche ce qui n'est pas un prix produit. Modifie si besoin. Tout sera validé par notre équipe.
            </div>
          </div>

          <div className="space-y-1.5 max-h-[55vh] overflow-y-auto pb-4">
            {extractedItems.map((it) => (
              <div
                key={it.idx}
                className="bg-white rounded-xl p-3 flex items-center gap-3"
                style={{
                  border: '1px solid ' + (it.selected ? '#A7F3D0' : '#EAEEF4'),
                  opacity: it.selected ? 1 : 0.5,
                }}
              >
                <input
                  type="checkbox"
                  checked={it.selected}
                  onChange={() => toggleItem(it.idx)}
                  style={{ transform: 'scale(1.2)', accentColor: '#16A34A' }}
                />
                <div className="flex-1 min-w-0">
                  <div className="font-bold text-sm text-ink truncate">{it.name_raw}</div>
                  <div className="text-[11px] text-slate flex items-center gap-2">
                    {it.matched_product_id ? (
                      <span style={{ color: '#15803D' }}>✓ Produit reconnu</span>
                    ) : (
                      <span style={{ color: '#F59E0B' }}>? À vérifier</span>
                    )}
                    {it.quantity && <span>· {it.quantity}</span>}
                    {it.confidence != null && (
                      <span>· {Math.round(it.confidence * 100)}%</span>
                    )}
                  </div>
                </div>
                <input
                  type="number"
                  value={it.price}
                  onChange={(e) => updateItemPrice(it.idx, e.target.value)}
                  className="w-20 px-2 py-1 rounded-lg text-sm font-bold text-right outline-none"
                  style={{ background: '#F1F4F9', border: '1px solid #EAEEF4' }}
                  inputMode="numeric"
                />
                <span className="text-xs font-bold text-slate">F</span>
              </div>
            ))}
          </div>

          <button
            onClick={confirmProposals}
            disabled={submitting || extractedItems.filter((i) => i.selected).length === 0}
            className="w-full px-5 py-4 rounded-2xl font-bold text-white shadow-md"
            style={{ background: submitting ? '#DDE3EC' : '#9333EA' }}
          >
            {submitting ? 'Envoi…' : `Envoyer ${extractedItems.filter((i) => i.selected).length} prix à validation`}
          </button>
        </div>
      )}

      {/* === Étape 5 : Confirmation === */}
      {step === 'done' && (
        <div className="bg-white rounded-2xl p-8 text-center" style={{ border: '1px solid #EAEEF4' }}>
          <div className="w-16 h-16 mx-auto mb-3 rounded-full flex items-center justify-center" style={{ background: '#ECFDF5' }}>
            <Check size={32} strokeWidth={2.5} style={{ color: '#15803D' }} />
          </div>
          <div className="font-display font-bold text-lg text-ink mb-2">Merci !</div>
          <div className="text-sm text-slate leading-relaxed mb-5">
            Tes prix seront validés par notre équipe sous 24-48h.<br />
            Une fois approuvés, ils apparaîtront dans le comparateur.
          </div>
          <button
            onClick={() => setActiveTab?.('home')}
            className="w-full px-5 py-3 rounded-2xl font-bold text-white"
            style={{ background: '#102A43' }}
          >
            Retour à l'accueil
          </button>
        </div>
      )}
    </div>
  );
};

window.PhotoForm = PhotoForm;
