// admin-editor.jsx — Formulario de carga/edición de vehículo
const { useState, useEffect, useRef } = React;

const CARROCERIAS = ["Sedán", "Hatchback", "SUV", "Pickup", "Coupé", "Utilitario", "Monovolumen", "Moto"];
const COMBUSTIBLES = ["Nafta", "Diésel", "Híbrido", "Eléctrico", "GNC"];
const TRANSMISIONES = ["Manual", "Automática", "CVT"];
const TAGS = ["", "DESTACADO", "PREMIUM", "NUEVO", "COLECCIÓN"];

// === PHOTO UPLOADER ===
const PhotoUploader = ({ photos, onChange, onAddBlob, onDeletePhoto }) => {
  const [drag, setDrag] = useState(false);
  const [dragIdx, setDragIdx] = useState(null);
  const [overIdx, setOverIdx] = useState(null);
  const fileInputRef = useRef();

  const handleFiles = async (files) => {
    const accepted = Array.from(files).filter(f => f.type.startsWith('image/'));
    for (const f of accepted) {
      await onAddBlob(f);
    }
  };

  const onDrop = (e) => {
    e.preventDefault(); setDrag(false);
    if (e.dataTransfer && e.dataTransfer.files) handleFiles(e.dataTransfer.files);
  };

  // Reorder
  const onTileDragStart = (i) => setDragIdx(i);
  const onTileDragOver = (e, i) => { e.preventDefault(); setOverIdx(i); };
  const onTileDrop = (e, i) => {
    e.preventDefault();
    if (dragIdx === null || dragIdx === i) { setDragIdx(null); setOverIdx(null); return; }
    const next = [...photos];
    const [moved] = next.splice(dragIdx, 1);
    next.splice(i, 0, moved);
    onChange(next);
    setDragIdx(null); setOverIdx(null);
  };

  return (
    <div className="uploader">
      <div
        className={`uploader-drop ${drag ? 'drag' : ''}`}
        onDragOver={(e)=>{e.preventDefault(); setDrag(true);}}
        onDragLeave={()=>setDrag(false)}
        onDrop={onDrop}
        onClick={()=>fileInputRef.current?.click()}
      >
        <div className="uploader-drop-icon">
          <AIcon.Upload width="22" height="22"/>
        </div>
        <div className="uploader-drop-title">Arrastr&aacute; las fotos acá</div>
        <div className="uploader-drop-sub">o hac&eacute; click para seleccionar · JPG, PNG, WEBP</div>
        <input
          ref={fileInputRef}
          type="file" accept="image/*" multiple
          style={{display:'none'}}
          onChange={(e)=>handleFiles(e.target.files)}
        />
      </div>

      {photos.length > 0 && (
        <React.Fragment>
          <div className="uploader-instructions">
            <strong>Arrastr&aacute; las fotos para reordenarlas.</strong> La primera es la portada que se muestra en el catálogo.
          </div>
          <div className="uploader-grid">
            {photos.map((p, i) => (
              <div
                key={p}
                className={`uploader-tile ${dragIdx === i ? 'dragging' : ''} ${overIdx === i && dragIdx !== i ? 'over' : ''}`}
                draggable
                onDragStart={()=>onTileDragStart(i)}
                onDragOver={(e)=>onTileDragOver(e, i)}
                onDrop={(e)=>onTileDrop(e, i)}
                onDragEnd={()=>{setDragIdx(null); setOverIdx(null);}}
              >
                <PhotoPreview src={p}/>
                <span className="uploader-tile-num">{String(i+1).padStart(2,'0')}</span>
                {i === 0 && <span className="uploader-tile-main">Portada</span>}
                <button
                  type="button"
                  className="uploader-tile-del"
                  onClick={(e)=>{e.stopPropagation(); onDeletePhoto(p, i);}}
                  title="Quitar foto"
                >
                  <AIcon.X width="13" height="13"/>
                </button>
              </div>
            ))}
          </div>
          <div className="adm-input-help">{photos.length} foto{photos.length === 1 ? '' : 's'} cargada{photos.length === 1 ? '' : 's'}</div>
        </React.Fragment>
      )}
    </div>
  );
};

// Resuelve idb:KEY a ObjectURL para previsualización
const PhotoPreview = ({ src }) => {
  const [resolved, setResolved] = useState(null);
  useEffect(() => {
    let cancelled = false;
    if (!src) { setResolved(null); return; }
    if (src.startsWith('idb:')) {
      window.OMEGA_STORE.resolvePhoto(src).then(url => {
        if (!cancelled) setResolved(url);
      });
    } else {
      setResolved(src);
    }
    return () => { cancelled = true; };
  }, [src]);
  if (!resolved) return null;
  return <img src={resolved} alt="" loading="lazy"/>;
};

// === EDITOR ===
const VehicleEditor = ({ vehicle, isNew, onSave, onCancel, onLogout }) => {
  const blank = {
    id: '', marca: '', modelo: '', anio: '', km: '', precio: '', combustible: 'Nafta',
    transmision: 'Manual', color: '', carroceria: 'Sedán', patente: '', tag: '',
    descripcion: '', equipamiento: '', photos: [], draft: true
  };
  const [form, setForm] = useState(() => {
    if (vehicle) return { ...blank, ...vehicle };
    return { ...blank, id: 'ome-' + Date.now().toString(36) };
  });
  const [saving, setSaving] = useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleAddBlob = async (blob) => {
    const ref = await window.OMEGA_STORE.addPhoto(form.patente || form.id, blob);
    setForm(f => ({ ...f, photos: [...(f.photos||[]), ref] }));
  };
  const handleDeletePhoto = async (src, idx) => {
    const next = (form.photos || []).filter((_,i) => i !== idx);
    setForm(f => ({ ...f, photos: next }));
    if (src) await window.OMEGA_STORE.deletePhoto(src);
  };
  const handleReorder = (next) => setForm(f => ({ ...f, photos: next }));

  const submit = async (publishMode) => {
    setSaving(true);
    const out = {
      ...form,
      marca: (form.marca||'').trim(),
      modelo: (form.modelo||'').trim(),
      color: (form.color||'').trim(),
      patente: (form.patente||'').trim().toUpperCase(),
      anio: form.anio ? parseInt(form.anio) : null,
      km: form.km ? parseInt(form.km) : 0,
      precio: form.precio ? parseFloat(form.precio) : 0,
      draft: publishMode === 'draft',   // draft = oculto de la web
      photos: form.photos || []
    };
    await onSave(out);
    setSaving(false);
  };

  return (
    <React.Fragment>
      <header className="adm-top">
        <div className="adm-top-row">
          <div className="adm-brand">
            <img src="logo-omega.png" alt="OMEGA"/>
            <div className="adm-brand-sub">Back-office <span className="accent">●</span></div>
          </div>
          <div className="adm-top-actions">
            <button className="btn btn-ghost btn-sm" onClick={onCancel}>
              <AIcon.X width="13" height="13"/> Cancelar
            </button>
            <button className="btn btn-ghost btn-sm" onClick={onLogout}>
              <AIcon.Logout width="13" height="13"/> Salir
            </button>
          </div>
        </div>
      </header>

      <main className="adm-main">
        <div className="adm-pagehead">
          <div>
            <div className="eyebrow">Gestión de fotos y vidriera</div>
            <h1>{form.marca || 'Veh\u00edculo'} {form.modelo}</h1>
          </div>
        </div>

        <div className="editor-wrap">
          {/* Datos */}
          <div className="editor-panel">
            <h3 className="editor-panel-title"><span className="editor-panel-title-num">1</span>Datos del auto</h3>
            <div className="sys-note">
              <AIcon.Logout width="13" height="13" style={{transform:'rotate(180deg)'}}/>
              Estos datos vienen de tu <strong>sistema de gestión</strong> y son de sólo lectura. Para cambiarlos, editá el auto en sistema.automotoresomega.com.
            </div>
            <div className="editor-grid">
              <div>
                <label className="adm-input-label">Marca</label>
                <input className="adm-input" value={form.marca} readOnly disabled/>
              </div>
              <div>
                <label className="adm-input-label">Modelo</label>
                <input className="adm-input" value={form.modelo} readOnly disabled/>
              </div>
              <div>
                <label className="adm-input-label">Año</label>
                <input className="adm-input" value={form.anio} readOnly disabled/>
              </div>
              <div>
                <label className="adm-input-label">Kilometraje</label>
                <input className="adm-input" value={form.km} readOnly disabled/>
              </div>
              <div>
                <label className="adm-input-label">Color</label>
                <input className="adm-input" value={form.color} readOnly disabled/>
              </div>
              <div>
                <label className="adm-input-label">Patente</label>
                <input className="adm-input" value={form.patente} readOnly disabled style={{textTransform:'uppercase'}}/>
              </div>
              <div className="editor-field-wide">
                <label className="adm-input-label">Precio publicado</label>
                <input className="adm-input" value={form.precio ? fmtPriceARS(parseFloat(form.precio)) : ''} readOnly disabled/>
              </div>
            </div>

            <h3 className="editor-panel-title" style={{marginTop:36}}><span className="editor-panel-title-num">2</span>Datos de vidriera</h3>
            <div className="adm-input-help" style={{marginBottom:16}}>Estos datos los controlás vos para que el auto se vea completo en la web.</div>
            <div className="editor-grid">
              <div>
                <label className="adm-input-label">Carrocería</label>
                <select className="adm-select" value={form.carroceria} onChange={(e)=>set('carroceria', e.target.value)}>
                  {CARROCERIAS.map(c => <option key={c}>{c}</option>)}
                </select>
              </div>
              <div>
                <label className="adm-input-label">Combustible</label>
                <select className="adm-select" value={form.combustible} onChange={(e)=>set('combustible', e.target.value)}>
                  {COMBUSTIBLES.map(c => <option key={c}>{c}</option>)}
                </select>
              </div>
              <div>
                <label className="adm-input-label">Transmisión</label>
                <select className="adm-select" value={form.transmision} onChange={(e)=>set('transmision', e.target.value)}>
                  {TRANSMISIONES.map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <label className="adm-input-label">&nbsp;</label>
                <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-mute)', letterSpacing:'0.1em', paddingTop:11}}>SE AUTODETECTAN DEL MODELO</div>
              </div>
              <div className="editor-field-wide">
                <label className="adm-input-label">Destacar como</label>
                <div className="adm-tag-picker">
                  {TAGS.map(t => (
                    <button
                      key={t || 'none'} type="button"
                      className={`adm-tag-opt ${form.tag === t ? 'on' : ''}`}
                      onClick={()=>set('tag', t)}
                    >
                      {t || 'Sin destacar'}
                    </button>
                  ))}
                </div>
              </div>
              <div className="editor-field-wide">
                <label className="adm-input-label">Descripción (opcional)</label>
                <textarea className="adm-textarea" value={form.descripcion} onChange={(e)=>set('descripcion', e.target.value)} placeholder="Detalles relevantes del vehículo, historia, estado, observaciones..." rows="3"/>
              </div>
              <div className="editor-field-wide">
                <label className="adm-input-label">Equipamiento (opcional, separado por comas)</label>
                <input className="adm-input" value={form.equipamiento} onChange={(e)=>set('equipamiento', e.target.value)} placeholder="Airbags, ABS, Climatizador, Cámara trasera, CarPlay..."/>
              </div>
            </div>
          </div>

          {/* Fotos */}
          <div className="editor-panel">
            <h3 className="editor-panel-title"><span className="editor-panel-title-num">2</span>Fotos del vehículo</h3>
            <PhotoUploader
              photos={form.photos || []}
              onChange={handleReorder}
              onAddBlob={handleAddBlob}
              onDeletePhoto={handleDeletePhoto}
            />
          </div>
        </div>

        <div className="editor-foot">
          <button className="btn btn-ghost" onClick={onCancel} disabled={saving}>Cancelar</button>
          <div className="editor-foot-actions">
            <button className="btn" onClick={()=>submit('draft')} disabled={saving}>Guardar y ocultar de la web</button>
            <button className="btn btn-accent" onClick={()=>submit('publish')} disabled={saving}>
              <AIcon.Check width="14" height="14"/> {saving ? 'Guardando...' : 'Guardar y mostrar en la web'}
            </button>
          </div>
        </div>
      </main>
    </React.Fragment>
  );
};

Object.assign(window, { PhotoUploader, VehicleEditor, PhotoPreview });
