import { useRef, useState } from 'react';

interface ProductData {
  id: string;
  name: string;
  sku?: string | null;
  normalized_category: string;
  dimensions?: string | null;
  thickness?: string | null;
  color?: string | null;
  origin?: string | null;
  price_without_vat_mxn?: number | null;
  vat_rate: number;
  coverage_m2_per_unit?: number | null;
  description?: string | null;
  image_urls: string[];
  stock_status: string;
  stock_quantity?: number | null;
  quote_enabled: boolean;
  requires_specialist_quote: boolean;
  active: boolean;
  sat_product_key?: string | null;
  sat_unit_key?: string | null;
  alegra_id?: string | null;
}
interface Option {
  value: string;
  label: string;
}
interface Props {
  product: ProductData;
  categories: Option[];
  units: Option[];
  stockStatuses: Option[];
}

export default function ProductEditor({ product, categories, units, stockStatuses }: Props) {
  const [p, setP] = useState<ProductData>({ ...product, image_urls: product.image_urls ?? [] });
  const [busy, setBusy] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [msg, setMsg] = useState<{ text: string; ok: boolean } | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  function set<K extends keyof ProductData>(key: K, value: ProductData[K]) {
    setP((prev) => ({ ...prev, [key]: value }));
  }
  function flash(text: string, ok = true) {
    setMsg({ text, ok });
    setTimeout(() => setMsg(null), 3500);
  }
  function num(v: string): number | null {
    if (v.trim() === '') return null;
    const n = Number(v);
    return Number.isFinite(n) ? n : null;
  }

  async function api(url: string, body?: unknown, method = 'POST') {
    const res = await fetch(url, {
      method,
      headers: body ? { 'content-type': 'application/json' } : undefined,
      body: body ? JSON.stringify(body) : undefined,
    });
    return res.json();
  }

  async function save() {
    setBusy(true);
    const json = await api(
      `/api/catalog/products/${p.id}`,
      {
        name: p.name,
        sku: p.sku || null,
        normalized_category: p.normalized_category,
        dimensions: p.dimensions || null,
        thickness: p.thickness || null,
        color: p.color || null,
        origin: p.origin || null,
        price_without_vat_mxn: p.price_without_vat_mxn,
        vat_rate: p.vat_rate,
        coverage_m2_per_unit: p.coverage_m2_per_unit,
        description: p.description || null,
        image_urls: p.image_urls,
        stock_status: p.stock_status,
        stock_quantity: p.stock_quantity,
        quote_enabled: p.quote_enabled,
        requires_specialist_quote: p.requires_specialist_quote,
        sat_product_key: p.sat_product_key || null,
        sat_unit_key: p.sat_unit_key || null,
        alegra_id: p.alegra_id || null,
      },
      'PATCH',
    );
    setBusy(false);
    if (json.ok) {
      setP((prev) => ({ ...prev, ...json.data }));
      flash('Producto guardado.');
    } else {
      flash(json.error || 'No se pudo guardar.', false);
    }
  }

  // ---- Galería ----
  async function onPickFiles(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files ?? []);
    if (files.length === 0) return;
    setUploading(true);
    let lastProduct: ProductData | null = null;
    for (const file of files) {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch(`/api/catalog/products/${p.id}/images`, { method: 'POST', body: fd });
      const json = await res.json();
      if (json.ok) {
        lastProduct = json.data.product as ProductData;
      } else {
        flash(json.error || `No se pudo subir ${file.name}.`, false);
      }
    }
    if (lastProduct) {
      setP((prev) => ({ ...prev, image_urls: lastProduct!.image_urls }));
      flash('Imagen(es) subida(s).');
    }
    setUploading(false);
    if (fileRef.current) fileRef.current.value = '';
  }

  function removeImage(url: string) {
    set('image_urls', p.image_urls.filter((u) => u !== url));
    flash('Imagen quitada. Guarda para confirmar.');
  }
  function makeMain(url: string) {
    set('image_urls', [url, ...p.image_urls.filter((u) => u !== url)]);
    flash('Imagen principal cambiada. Guarda para confirmar.');
  }
  function move(url: string, dir: -1 | 1) {
    const arr = [...p.image_urls];
    const i = arr.indexOf(url);
    const j = i + dir;
    if (i < 0 || j < 0 || j >= arr.length) return;
    const tmp = arr[i] as string;
    arr[i] = arr[j] as string;
    arr[j] = tmp;
    set('image_urls', arr);
  }

  async function togglePublish() {
    setBusy(true);
    const json = await api(`/api/catalog/products/${p.id}/${p.active ? 'unpublish' : 'publish'}`);
    setBusy(false);
    if (json.ok) {
      set('active', json.data.active);
      flash(json.data.active ? 'Producto publicado.' : 'Producto despublicado.');
    } else flash(json.error || 'No se pudo cambiar el estatus.', false);
  }

  async function archive() {
    if (!window.confirm('¿Archivar (soft delete) este producto? Dejará de aparecer en el catálogo.')) return;
    setBusy(true);
    const json = await api(`/api/catalog/products/${p.id}`, undefined, 'DELETE');
    setBusy(false);
    if (json.ok) {
      flash('Producto archivado. Redirigiendo…');
      setTimeout(() => (window.location.href = '/crm/productos'), 900);
    } else flash(json.error || 'No se pudo archivar.', false);
  }

  const stockColor =
    p.stock_status === 'in_stock'
      ? 'var(--pf-success)'
      : p.stock_status === 'out_of_stock'
        ? 'var(--pf-danger,#ff7a8a)'
        : 'var(--pf-warning)';

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {msg && (
        <p className="notice" style={{ color: msg.ok ? 'var(--pf-success)' : '#ff7a8a' }}>{msg.text}</p>
      )}

      {/* Estatus */}
      <div className="card" style={{ padding: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
        <div>
          <span className="muted" style={{ fontSize: '.78rem', textTransform: 'uppercase', letterSpacing: '.06em' }}>Estatus</span>
          <div><strong style={{ color: p.active ? 'var(--pf-success)' : 'var(--pf-warning)' }}>{p.active ? 'Publicado' : 'Inactivo'}</strong></div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary" style={{ width: 'auto' }} disabled={busy} onClick={togglePublish}>
            {p.active ? 'Despublicar' : 'Publicar'}
          </button>
          <button className="btn btn-secondary" style={{ width: 'auto', color: 'var(--pf-danger,#ff7a8a)' }} disabled={busy} onClick={archive}>
            Archivar
          </button>
        </div>
      </div>

      {/* Galería de imágenes */}
      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Galería de imágenes</h2>
        <p className="muted" style={{ fontSize: '.82rem', marginBottom: 12 }}>
          La primera imagen es la principal en el catálogo y la ficha. JPG, PNG, WEBP, AVIF o GIF · máx. 5&nbsp;MB.
        </p>

        {p.image_urls.length === 0 ? (
          <p className="notice" style={{ marginBottom: 12 }}>Sin imágenes propias. Se usa la imagen genérica por categoría.</p>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(132px, 1fr))', gap: 12, marginBottom: 12 }}>
            {p.image_urls.map((url, i) => (
              <figure key={url} style={{ margin: 0, border: '1px solid var(--pf-border)', borderRadius: 'var(--pf-radius, 10px)', overflow: 'hidden', background: 'var(--pf-bg-2)' }}>
                <div style={{ position: 'relative', aspectRatio: '4 / 3', background: 'var(--pf-surface-3, #1a1c22)' }}>
                  <img src={url} alt={`Imagen ${i + 1} de ${p.name}`} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                  {i === 0 && (
                    <span style={{ position: 'absolute', top: 6, left: 6, fontSize: '.66rem', fontWeight: 700, background: 'var(--pf-accent, #2e2ed6)', color: '#fff', padding: '2px 7px', borderRadius: 999 }}>
                      Principal
                    </span>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 4, padding: 6, flexWrap: 'wrap' }}>
                  <button type="button" className="chip" style={{ cursor: 'pointer', flex: '1 1 auto' }} disabled={i === 0} onClick={() => makeMain(url)} title="Marcar como principal">★</button>
                  <button type="button" className="chip" style={{ cursor: 'pointer' }} disabled={i === 0} onClick={() => move(url, -1)} title="Mover antes">↑</button>
                  <button type="button" className="chip" style={{ cursor: 'pointer' }} disabled={i === p.image_urls.length - 1} onClick={() => move(url, 1)} title="Mover después">↓</button>
                  <button type="button" className="chip" style={{ cursor: 'pointer', color: 'var(--pf-danger,#ff7a8a)' }} onClick={() => removeImage(url)} title="Quitar">✕</button>
                </div>
              </figure>
            ))}
          </div>
        )}

        <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp,image/avif,image/gif" multiple style={{ display: 'none' }} onChange={onPickFiles} />
        <button type="button" className="btn btn-secondary" style={{ width: 'auto' }} disabled={uploading} onClick={() => fileRef.current?.click()}>
          {uploading ? 'Subiendo…' : '+ Subir imágenes'}
        </button>
      </div>

      {/* Inventario / Stock */}
      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Inventario</h2>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <div className="field" style={{ flex: '1 1 200px', marginBottom: 0 }}>
            <label>Disponibilidad</label>
            <select className="select" value={p.stock_status} onChange={(e) => set('stock_status', e.target.value)}>
              {stockStatuses.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}
            </select>
          </div>
          <div className="field" style={{ flex: '1 1 160px', marginBottom: 0 }}>
            <label>Existencias (piezas/unidades)</label>
            <input className="input" type="number" min="0" step="1" value={p.stock_quantity ?? ''} placeholder="Opcional" onChange={(e) => set('stock_quantity', num(e.target.value))} />
          </div>
          <div style={{ flex: '0 0 auto', paddingBottom: 8 }}>
            <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 999, background: stockColor, marginRight: 6 }} />
            <strong style={{ color: stockColor }}>{stockStatuses.find((s) => s.value === p.stock_status)?.label ?? p.stock_status}</strong>
          </div>
        </div>
      </div>

      {/* Datos comerciales */}
      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Datos comerciales</h2>
        <div className="field">
          <label>Nombre</label>
          <input className="input" value={p.name} onChange={(e) => set('name', e.target.value)} />
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="field" style={{ flex: '1 1 160px' }}>
            <label>SKU</label>
            <input className="input" value={p.sku ?? ''} onChange={(e) => set('sku', e.target.value)} />
          </div>
          <div className="field" style={{ flex: '1 1 200px' }}>
            <label>Categoría</label>
            <select className="select" value={p.normalized_category} onChange={(e) => set('normalized_category', e.target.value)}>
              {categories.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
            </select>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="field" style={{ flex: '1 1 140px' }}>
            <label>Precio sin IVA (MXN)</label>
            <input className="input" type="number" step="0.01" value={p.price_without_vat_mxn ?? ''} onChange={(e) => set('price_without_vat_mxn', num(e.target.value))} />
          </div>
          <div className="field" style={{ flex: '1 1 120px' }}>
            <label>IVA (0–1)</label>
            <input className="input" type="number" step="0.01" value={p.vat_rate} onChange={(e) => set('vat_rate', Number(e.target.value) || 0)} />
          </div>
          <div className="field" style={{ flex: '1 1 140px' }}>
            <label>Cobertura m²/unidad</label>
            <input className="input" type="number" step="0.0001" value={p.coverage_m2_per_unit ?? ''} onChange={(e) => set('coverage_m2_per_unit', num(e.target.value))} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="field" style={{ flex: '1 1 120px' }}><label>Dimensiones</label><input className="input" value={p.dimensions ?? ''} onChange={(e) => set('dimensions', e.target.value)} /></div>
          <div className="field" style={{ flex: '1 1 100px' }}><label>Espesor</label><input className="input" value={p.thickness ?? ''} onChange={(e) => set('thickness', e.target.value)} /></div>
          <div className="field" style={{ flex: '1 1 100px' }}><label>Color</label><input className="input" value={p.color ?? ''} onChange={(e) => set('color', e.target.value)} /></div>
          <div className="field" style={{ flex: '1 1 120px' }}><label>Procedencia</label><input className="input" value={p.origin ?? ''} onChange={(e) => set('origin', e.target.value)} /></div>
        </div>
        <div className="field" style={{ marginBottom: 0 }}>
          <label>Descripción</label>
          <textarea className="textarea" rows={4} value={p.description ?? ''} onChange={(e) => set('description', e.target.value)} />
        </div>
      </div>

      {/* Cotización */}
      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Cotización</h2>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '10px 0', cursor: 'pointer' }}>
          <input type="checkbox" checked={p.quote_enabled} onChange={(e) => set('quote_enabled', e.target.checked)} />
          <span>Participa en cotización automática por m²</span>
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={p.requires_specialist_quote} onChange={(e) => set('requires_specialist_quote', e.target.checked)} />
          <span>Requiere validación de especialista</span>
        </label>
      </div>

      {/* Fiscal SAT / Alegra */}
      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Fiscal (SAT) · facturación Alegra</h2>
        <p className="muted" style={{ fontSize: '.82rem', marginBottom: 8 }}>Necesarios para facturar (CFDI 4.0). Ver docs/INTEGRATION_ALEGRA.md.</p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="field" style={{ flex: '1 1 160px' }}>
            <label>Clave producto/servicio SAT</label>
            <input className="input" value={p.sat_product_key ?? ''} onChange={(e) => set('sat_product_key', e.target.value)} placeholder="Ej. 30181600" />
          </div>
          <div className="field" style={{ flex: '1 1 160px' }}>
            <label>Clave de unidad SAT</label>
            <select className="select" value={p.sat_unit_key ?? ''} onChange={(e) => set('sat_unit_key', e.target.value)}>
              <option value="">—</option>
              {units.map((u) => <option key={u.value} value={u.value}>{u.label}</option>)}
            </select>
          </div>
        </div>
        <div className="field" style={{ marginBottom: 0 }}>
          <label>ID de Alegra (mapeo)</label>
          <input className="input" value={p.alegra_id ?? ''} onChange={(e) => set('alegra_id', e.target.value)} placeholder="Se llena al sincronizar (Etapa 2)" />
        </div>
      </div>

      <button className="btn btn-primary" disabled={busy} onClick={save}>
        {busy ? 'Guardando…' : 'Guardar producto'}
      </button>
    </div>
  );
}
