/* Inventario — SKU, precio y stock por talla. La vitrina se configura en Tienda online. */

const DEFAULT_INVENTORY_FORM = {
  sku: '',
  name: '',
  category: 'Uniformes',
  price: 0,
  stock_by_size: {},
};

const buildEmptyStockBySize = () => {
  const o = {};
  PRODUCT_SIZE_OPTIONS.forEach(s => { o[s] = 0; });
  return o;
};

const formatStockBreakdown = (stockBySize) => {
  const by = stockBySize || {};
  const lines = PRODUCT_SIZE_OPTIONS
    .map(size => ({ size, qty: Math.max(0, Number(by[size]) || 0) }))
    .filter(row => row.qty > 0);
  const total = sumStockBySize(by);
  return { lines, total };
};

const StockBySizeSummary = ({ theme, stockBySize, compact }) => {
  const { lines, total } = formatStockBreakdown(stockBySize);
  if (compact) {
    const parts = lines.map(l => `${l.size}: ${l.qty}`);
    return (
      <span style={{ fontFamily: 'Inter, sans-serif' }}>
        {parts.length ? `${parts.join(' · ')} · ` : ''}
        <strong style={{ color: theme.primary }}>Total {total}</strong>
      </span>
    );
  }
  return (
    <div style={{
      marginTop: 12, padding: 12, borderRadius: 10,
      border: `1px solid ${theme.border}`, background: theme.bg,
    }}>
      <div style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', marginBottom: 8, fontFamily: 'Inter, sans-serif' }}>
        Conteo por talla
      </div>
      {lines.length === 0 ? (
        <p style={{ margin: 0, fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>
          Aún no hay piezas en ninguna talla.
        </p>
      ) : (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
          {lines.map(({ size, qty }) => (
            <span key={size} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '5px 10px', borderRadius: 8,
              background: theme.bgInput, border: `1px solid ${theme.border}`,
              fontFamily: 'Inter, sans-serif', fontSize: 12,
            }}>
              <span style={{ fontWeight: 700, color: theme.text }}>{size}</span>
              <span style={{ color: theme.textMute }}>·</span>
              <span style={{ fontWeight: 700, color: theme.primary }}>{qty}</span>
              <span style={{ fontSize: 10, color: theme.textDim }}>pza.</span>
            </span>
          ))}
        </div>
      )}
      <div style={{
        paddingTop: 10, borderTop: `1px solid ${theme.border}`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontFamily: 'Inter, sans-serif',
      }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: theme.text, textTransform: 'uppercase', letterSpacing: 0.4 }}>
          Total general
        </span>
        <span style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 28, color: theme.primary, letterSpacing: 1 }}>
          {total} <span style={{ fontSize: 14, fontFamily: 'Inter, sans-serif', fontWeight: 600, color: theme.textDim }}>piezas</span>
        </span>
      </div>
    </div>
  );
};

const ProductInventoryFormModal = ({ open, onClose, theme, form, onChange, onSave, saving, error }) => (
  <Modal open={open} onClose={onClose} theme={theme} title={form._editId ? 'Editar inventario' : 'Nuevo producto'} width={640}>
    <div style={{ padding: '8px 24px 24px', display: 'grid', gap: 14, maxHeight: '75vh', overflowY: 'auto' }}>
      <p style={{ margin: 0, fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif', lineHeight: 1.5 }}>
        Al guardar, el producto aparece en <strong>Admin → Tienda online</strong> para subir fotos y elegir si se muestra en el landing o en la tienda completa.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Input theme={theme} label="SKU" value={form.sku} onChange={e => onChange('sku', e.target.value)} />
        <Input theme={theme} label="Nombre *" value={form.name} onChange={e => onChange('name', e.target.value)} />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Input theme={theme} label="Categoría" value={form.category} onChange={e => onChange('category', e.target.value)} />
        <Input theme={theme} label="Precio" type="number" value={form.price} onChange={e => onChange('price', e.target.value)} />
      </div>
      <div>
        <label style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>
          Inventario por talla
        </label>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(88px, 1fr))',
          gap: 8, marginTop: 8,
        }}>
          {PRODUCT_SIZE_OPTIONS.map(size => {
            const qty = Math.max(0, Number(form.stock_by_size?.[size]) || 0);
            return (
            <div key={size}>
              <label style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, fontFamily: 'Inter, sans-serif' }}>
                {size}
                {qty > 0 && (
                  <span style={{ marginLeft: 4, color: theme.primary, fontWeight: 800 }}>({qty})</span>
                )}
              </label>
              <input
                type="number"
                min="0"
                value={form.stock_by_size?.[size] ?? 0}
                onChange={e => onChange('stock_size', { size, qty: e.target.value })}
                style={{
                  width: '100%', marginTop: 4, padding: '8px 10px', borderRadius: 8,
                  border: `1px solid ${theme.border}`, background: theme.bgInput, color: theme.text,
                  fontFamily: 'Inter, sans-serif', fontSize: 13,
                }}
              />
            </div>
            );
          })}
        </div>
        <StockBySizeSummary theme={theme} stockBySize={form.stock_by_size} />
      </div>
      {error && <div style={{ color: theme.danger, fontSize: 13, fontFamily: 'Inter, sans-serif' }}>{error}</div>}
    </div>
    <div style={{ padding: '16px 24px', borderTop: `1px solid ${theme.border}`, display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
      <Btn theme={theme} kind="ghost" onClick={onClose}>Cancelar</Btn>
      <Btn theme={theme} icon="check" onClick={onSave} disabled={saving}>{saving ? 'Guardando…' : 'Guardar'}</Btn>
    </div>
  </Modal>
);

const formatMovementDate = (iso) => {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
  } catch {
    return iso;
  }
};

const InventoryResetModal = (typeof window !== 'undefined' && typeof window.InventoryResetHistoryModal === 'function')
  ? window.InventoryResetHistoryModal
  : () => null;

const InventorySalesHistory = ({ theme, products }) => {
  const [productFilter, setProductFilter] = React.useState('');
  const [resetOpen, setResetOpen] = React.useState(false);
  const [resetBusy, setResetBusy] = React.useState(false);
  const [resetErr, setResetErr] = React.useState('');
  const [pwOpen, setPwOpen] = React.useState(false);
  const [pwBusy, setPwBusy] = React.useState(false);
  const [pwErr, setPwErr] = React.useState('');
  const { unlocked: invResetUnlocked, unlock: invResetUnlock, lock: invResetLock } = useInventoryResetUnlock();
  const InvPwModal = (typeof window !== 'undefined' && window.InventoryResetPasswordModal) || (() => null);
  const InvResetBtn = (typeof window !== 'undefined' && window.InventoryResetUnlockedButton) || (() => null);
  const { rows: movements, loading, error, reload } = useAdminList(
    () => (typeof fetchInventoryMovements === 'function'
      ? fetchInventoryMovements({ productId: productFilter || null, limit: 200 })
      : Promise.resolve([])),
    [productFilter]
  );

  React.useEffect(() => {
    const on = () => reload();
    window.addEventListener('tecos:orders-changed', on);
    window.addEventListener('tecos:comprobantes-changed', on);
    window.addEventListener('tecos:products-changed', on);
    return () => {
      window.removeEventListener('tecos:orders-changed', on);
      window.removeEventListener('tecos:comprobantes-changed', on);
      window.removeEventListener('tecos:products-changed', on);
    };
  }, [reload]);

  const openReset = () => { setResetErr(''); setResetOpen(true); };
  const openPw = () => { setPwErr(''); setPwOpen(true); };
  const verifyPw = async (password) => {
    setPwBusy(true);
    setPwErr('');
    try {
      await verifyAdminSessionPassword(password);
      invResetUnlock();
      setPwOpen(false);
    } catch (e) {
      setPwErr(e.message || 'Contraseña incorrecta.');
    }
    setPwBusy(false);
  };

  const runResetHistory = async () => {
    if (typeof resetInventoryMovementsHistory !== 'function') {
      setResetErr('Función no cargada. Recarga la página.');
      return;
    }
    setResetBusy(true);
    setResetErr('');
    try {
      const { deleted } = await resetInventoryMovementsHistory();
      setResetOpen(false);
      reload();
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('tecos:products-changed'));
        window.dispatchEvent(new CustomEvent('tecos:inventory-history-reset'));
      }
    } catch (e) {
      setResetErr(e.message || 'No se pudo reiniciar el historial.');
    }
    setResetBusy(false);
  };

  const soldUnits = (movements || []).reduce((s, m) => s + Math.abs(Number(m.qty_delta) || 0), 0);
  const orderIds = new Set((movements || []).map(m => m.order_id).filter(Boolean));
  const byProduct = React.useMemo(() => {
    const map = {};
    (movements || []).forEach((m) => {
      const key = m.product_id || m.product_name;
      if (!map[key]) map[key] = { name: m.product_name, sku: m.product_sku, units: 0, lines: 0 };
      map[key].units += Math.abs(Number(m.qty_delta) || 0);
      map[key].lines += 1;
    });
    return Object.values(map).sort((a, b) => b.units - a.units);
  }, [movements]);

  return (
    <div style={{ marginTop: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12, marginBottom: 16 }}>
        <div
          onClick={(e) => onInventoryResetRevealGesture(e, {
            unlocked: invResetUnlocked,
            onNeedPassword: openPw,
            onOpenReset: openReset,
          })}
          style={{ userSelect: 'none' }}
        >
          <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.text, letterSpacing: 1, margin: 0, fontWeight: 400 }}>
            HISTORIAL DE COMPRAS Y DESCUENTOS
          </h3>
          <p style={{ margin: '6px 0 0', fontSize: 13, color: theme.textDim, fontFamily: 'Inter, sans-serif', maxWidth: 640 }}>
            Cada venta confirmada en <strong>Verificar comprobantes → Tienda</strong> descuenta piezas por talla. Aquí ves qué se vendió y el stock antes/después.
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <Btn theme={theme} kind="ghost" size="sm" icon="history" onClick={reload} disabled={loading}>Actualizar</Btn>
          {invResetUnlocked && (
            <InvResetBtn
              theme={theme}
              onClick={openReset}
              busy={resetBusy}
              onLock={invResetLock}
              label="Reiniciar historial"
            />
          )}
        </div>
      </div>

      <InvPwModal
        theme={theme}
        open={pwOpen}
        onClose={() => !pwBusy && setPwOpen(false)}
        onVerify={verifyPw}
        busy={pwBusy}
        err={pwErr}
      />

      <InventoryResetModal
        theme={theme}
        open={resetOpen}
        onClose={() => !resetBusy && setResetOpen(false)}
        onConfirm={runResetHistory}
        busy={resetBusy}
        err={resetErr}
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12, marginBottom: 16 }}>
        {[
          { l: 'Piezas descontadas', v: String(soldUnits), c: theme.primary },
          { l: 'Órdenes confirmadas', v: String(orderIds.size), c: theme.success },
          { l: 'Movimientos', v: String((movements || []).length), c: theme.info },
        ].map((s) => (
          <Card key={s.l} theme={theme} style={{ padding: 14 }}>
            <div style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>{s.l}</div>
            <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 28, color: s.c, marginTop: 4 }}>{s.v}</div>
          </Card>
        ))}
      </div>

      {byProduct.length > 0 && (
        <Card theme={theme} style={{ padding: 14, marginBottom: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: theme.textMute, textTransform: 'uppercase', marginBottom: 10, fontFamily: 'Inter, sans-serif' }}>
            Resumen por producto
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {byProduct.map((p, i) => (
              <span key={i} style={{
                padding: '6px 12px', borderRadius: 8, background: theme.bgInput,
                border: `1px solid ${theme.border}`, fontSize: 12, fontFamily: 'Inter, sans-serif',
              }}>
                <strong style={{ color: theme.text }}>{p.name}</strong>
                <span style={{ color: theme.textDim }}> · −{p.units} pza. · {p.lines} línea(s)</span>
              </span>
            ))}
          </div>
        </Card>
      )}

      <div style={{ marginBottom: 12, maxWidth: 320 }}>
        <label style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>
          Filtrar por producto
        </label>
        <select
          value={productFilter}
          onChange={(e) => setProductFilter(e.target.value)}
          style={{
            width: '100%', marginTop: 6, padding: '10px 12px', borderRadius: 8,
            border: `1px solid ${theme.border}`, background: theme.bgInput, color: theme.text,
            fontFamily: 'Inter, sans-serif', fontSize: 13,
          }}
        >
          <option value="">Todos los productos</option>
          {(products || []).map((p) => (
            <option key={p.id} value={p.id}>{p.name}{p.sku ? ` (${p.sku})` : ''}</option>
          ))}
        </select>
      </div>

      <Card theme={theme} style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 32 }}><LoadingBlock theme={theme} label="Cargando historial…" /></div>
        ) : error ? (
          <EmptyState theme={theme} title="Error" message={error} icon="warning" />
        ) : !(movements || []).length ? (
          <EmptyState
            theme={theme}
            title="Sin movimientos aún"
            message="Al confirmar órdenes de tienda se registrarán aquí los descuentos por talla. Si ya confirmaste ventas antes, ejecuta la migración 051 en Supabase para importar el historial."
            icon="box"
          />
        ) : (
          <div className="tecos-table-scroll" style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'Inter, sans-serif', minWidth: 720 }}>
              <thead>
                <tr style={{ background: theme.bgInput, borderBottom: `1px solid ${theme.border}` }}>
                  {['Fecha', 'Orden', 'Alumno', 'Producto', 'Talla', 'Descontado', 'Stock', 'Tipo'].map((h) => (
                    <th key={h} style={{
                      padding: '12px 14px', textAlign: 'left', fontSize: 10, fontWeight: 700,
                      color: theme.textMute, letterSpacing: 1, textTransform: 'uppercase', whiteSpace: 'nowrap',
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {(movements || []).map((m, i) => {
                  const qty = Math.abs(Number(m.qty_delta) || 0);
                  const stockCell = m.stock_before != null && m.stock_after != null
                    ? `${m.stock_before} → ${m.stock_after}`
                    : '—';
                  return (
                    <tr key={m.id || i} style={{ borderBottom: `1px solid ${theme.border}` }}>
                      <td style={tdStyle(theme)}>{formatMovementDate(m.created_at)}</td>
                      <td style={tdStyle(theme)}>
                        <span style={{ fontWeight: 700, color: theme.primary, fontSize: 12 }}>{m.order_number || '—'}</span>
                      </td>
                      <td style={tdStyle(theme)}>
                        <div style={{ fontSize: 12, fontWeight: 600 }}>{m.student_name || '—'}</div>
                        <div style={{ fontSize: 11, color: theme.textMute }}>{m.student_code || ''}</div>
                      </td>
                      <td style={tdStyle(theme)}>
                        <div style={{ fontWeight: 600 }}>{m.product_name}</div>
                        {m.product_sku && <div style={{ fontSize: 10, color: theme.textMute }}>{m.product_sku}</div>}
                      </td>
                      <td style={tdStyle(theme)}><strong>{m.size}</strong></td>
                      <td style={tdStyle(theme)}>
                        <span style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 18, color: theme.danger }}>−{qty}</span>
                      </td>
                      <td style={tdStyle(theme)}>{stockCell}</td>
                      <td style={tdStyle(theme)}>
                        <span style={{
                          fontSize: 10, fontWeight: 700, textTransform: 'uppercase',
                          color: m.movement_type === 'venta' ? theme.success : theme.warning,
                        }}>{m.movement_type || 'venta'}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
};

const ProductInventoryModule = ({ theme }) => {
  const { rows, loading, error, needsAuth, reload } = useAdminList(() => fetchAllProducts(), []);
  const [modal, setModal] = React.useState(null);
  const [form, setForm] = React.useState({ ...DEFAULT_INVENTORY_FORM, stock_by_size: buildEmptyStockBySize() });
  const [saving, setSaving] = React.useState(false);
  const [formErr, setFormErr] = React.useState('');

  const openNew = () => {
    setForm({ ...DEFAULT_INVENTORY_FORM, stock_by_size: buildEmptyStockBySize(), _editId: null });
    setFormErr('');
    setModal('new');
  };

  const openEdit = (r) => {
    setForm({
      sku: r.sku || '',
      name: r.name,
      category: r.category,
      price: r.price,
      stock_by_size: { ...buildEmptyStockBySize(), ...parseStockBySize(r) },
      _editId: r.id,
    });
    setFormErr('');
    setModal(r.id);
  };

  const onChange = (key, val) => {
    if (key === 'stock_size') {
      setForm(f => ({
        ...f,
        stock_by_size: { ...f.stock_by_size, [val.size]: Math.max(0, Number(val.qty) || 0) },
      }));
      return;
    }
    setForm(f => ({ ...f, [key]: val }));
  };

  const save = async () => {
    if (!form.name?.trim()) { setFormErr('El nombre es obligatorio.'); return; }
    setSaving(true);
    setFormErr('');
    try {
      const { _editId, ...payload } = form;
      await upsertProductInventory(payload, _editId || null);
      notifyProductsChanged();
      setModal(null);
      reload();
    } catch (e) { setFormErr(e.message); }
    setSaving(false);
  };

  const del = async (id) => {
    if (!confirm('¿Eliminar producto del inventario y tienda?')) return;
    try {
      await deleteProduct(id);
      notifyProductsChanged();
      reload();
    } catch (e) { alert(e.message); }
  };

  const stockSummary = (r) => (
    <StockBySizeSummary theme={theme} stockBySize={parseStockBySize(r)} compact />
  );

  return (
    <AdminEntityShell theme={theme} title="INVENTARIO" sub="Stock, precios e historial de ventas que descontaron inventario." icon="box" onAdd={openNew}>
      {needsAuth ? <AuthRequired theme={theme} onRetry={reload} /> : loading ? <LoadingBlock theme={theme} /> : error ? (
        <EmptyState theme={theme} title="Error" message={error} />
      ) : (
        <Card theme={theme} style={{ padding: 0 }}>
          {rows.length === 0 ? <EmptyState theme={theme} title="Sin productos" icon="box" /> : rows.map(r => (
            <div key={r.id} style={{ padding: 14, borderBottom: `1px solid ${theme.border}`, display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700 }}>{r.name}</div>
                <div style={{ fontSize: 12, color: theme.textDim }}>
                  ${r.price} · {stockSummary(r)}
                  {r.active !== false ? ' · Configurado en tienda' : ' · Pendiente en Tienda online'}
                </div>
              </div>
              <RowActions theme={theme} onEdit={() => openEdit(r)} onDelete={() => del(r.id)} />
            </div>
          ))}
        </Card>
      )}

      <InventorySalesHistory theme={theme} products={rows} />

      <ProductInventoryFormModal
        open={!!modal}
        onClose={() => setModal(null)}
        theme={theme}
        form={form}
        onChange={onChange}
        onSave={save}
        saving={saving}
        error={formErr}
      />
    </AdminEntityShell>
  );
};

Object.assign(window, { ProductInventoryModule, ProductInventoryFormModal, buildEmptyStockBySize });
