{% extends "base.html" %}
{% block title %}{% if prod %}Editar Producto{% else %}Nuevo Producto{% endif %}{% endblock %}
{% block page_title %}{% if prod %}Editar Producto{% else %}Nuevo Producto{% endif %}{% endblock %}

{% block content %}
<div class="row justify-content-center">
  <div class="col-lg-7">

    {% if inv_stats and prod.producto_id %}
    <div class="card mb-3 border-primary-subtle">
      <div class="card-header py-2 bg-primary-subtle text-primary-emphasis d-flex align-items-center gap-2">
        <i class="bi bi-boxes"></i>
        <span class="fw-semibold">Datos de inventario (solo lectura)</span>
        <a href="{{ url_for('productos.ficha', id=prod.producto_id) }}"
           class="ms-auto btn btn-sm btn-outline-primary">
          <i class="bi bi-box-arrow-up-right me-1"></i>Ver ficha completa
        </a>
      </div>
      <div class="card-body py-2">
        <div class="row g-3 text-center">
          <div class="col-6 col-sm-3">
            <div class="text-muted small">Stock actual</div>
            <div class="fw-bold fs-5
              {% if inv_stats.stock_disponible <= 0 %}text-danger
              {% elif inv_stats.stock_minimo > 0 and inv_stats.stock_disponible < inv_stats.stock_minimo %}text-warning
              {% else %}text-success{% endif %}">
              {{ "%.0f"|format(inv_stats.stock_disponible or 0) }}
            </div>
            {% if inv_stats.stock_minimo > 0 %}
            <div class="text-muted" style="font-size:.75rem">mín {{ inv_stats.stock_minimo|int }}</div>
            {% endif %}
          </div>
          <div class="col-6 col-sm-3">
            <div class="text-muted small">Total comprado</div>
            <div class="fw-bold fs-5">{{ "%.0f"|format(inv_stats.total_comprado or 0) }}</div>
          </div>
          <div class="col-6 col-sm-3">
            <div class="text-muted small">Precio medio compra</div>
            <div class="fw-bold fs-5">
              {% if inv_stats.precio_medio_compra %}{{ "%.2f"|format(inv_stats.precio_medio_compra) }} €
              {% else %}—{% endif %}
            </div>
          </div>
          <div class="col-6 col-sm-3">
            <div class="text-muted small">Última compra</div>
            <div class="fw-bold fs-5 small">{{ inv_stats.ultima_compra or '—' }}</div>
          </div>
        </div>
      </div>
    </div>
    {% endif %}

    <div class="card">
      <div class="card-body p-4">
        <form method="post">

          <div class="mb-3">
            <label class="form-label fw-semibold">Nombre <span class="text-danger">*</span></label>
            <input type="text" name="nombre" class="form-control"
                   value="{{ prod.nombre if prod else '' }}"
                   placeholder="Ej: Camiseta talla M" required autofocus>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Descripción</label>
            <textarea name="descripcion" class="form-control" rows="2"
                      placeholder="Descripción breve (opcional)">{{ prod.descripcion if prod and prod.descripcion else '' }}</textarea>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Proveedor principal</label>
            <select name="proveedor_id" class="form-select">
              <option value="">— Sin proveedor —</option>
              {% for pv in proveedores %}
              <option value="{{ pv.id }}"
                {% if prod and prod.proveedor_id == pv.id %}selected{% endif %}>
                {{ pv.nombre }}
              </option>
              {% endfor %}
            </select>
          </div>

          <div class="row g-3 mb-3">
            <div class="col-sm-4">
              <label class="form-label fw-semibold">Precio de venta (€)</label>
              <input type="number" name="precio" class="form-control" step="0.01" min="0"
                     value="{{ prod.precio if prod else '0.00' }}">
            </div>
            <div class="col-sm-4">
              <label class="form-label fw-semibold">Precio de coste (€)</label>
              <input type="number" name="coste" class="form-control" step="0.01" min="0"
                     value="{{ prod.coste if prod else '0.00' }}"
                     placeholder="Ref. de compra">
            </div>
            <div class="col-sm-4">
              <label class="form-label fw-semibold">IVA (%)</label>
              <select name="iva_pct" class="form-select">
                {% for pct in [0, 4, 10, 21] %}
                <option value="{{ pct }}"
                  {% if prod and prod.iva_pct == pct %}selected
                  {% elif not prod and pct == 21 %}selected
                  {% endif %}>{{ pct }}%</option>
                {% endfor %}
              </select>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Unidad</label>
            <input type="text" name="unidad" class="form-control" style="max-width:140px"
                   value="{{ prod.unidad if prod else 'ud' }}"
                   placeholder="ud, h, kg, m²…">
          </div>

          {% if prod %}
          <div class="mb-4 form-check">
            <input type="checkbox" name="activo" id="activo" class="form-check-input"
                   {% if prod.activo %}checked{% endif %}>
            <label class="form-check-label" for="activo">Activo (aparece en autocompletado de facturas)</label>
          </div>
          {% endif %}

          <div id="margen-box" class="alert alert-secondary py-2 mb-4 d-flex align-items-center gap-3" style="display:none!important">
            <i class="bi bi-graph-up"></i>
            <span>Margen: <strong id="margen-pct" class="text-success">—</strong>
              (<span id="margen-abs">—</span> € / ud)</span>
          </div>

          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-check-lg me-1"></i>
              {% if prod %}Guardar cambios{% else %}Añadir al catálogo{% endif %}
            </button>
            <a href="{{ url_for('catalogo.lista') }}" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </form>
      </div>
    </div>

  </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
(function() {
  const precio = document.querySelector('input[name="precio"]');
  const coste  = document.querySelector('input[name="coste"]');
  const box    = document.getElementById('margen-box');
  const pct    = document.getElementById('margen-pct');
  const abs    = document.getElementById('margen-abs');

  function actualizar() {
    const p = parseFloat(precio.value) || 0;
    const c = parseFloat(coste.value)  || 0;
    if (c > 0 && p > 0) {
      const m = (p - c) / c * 100;
      pct.textContent = m.toFixed(1) + '%';
      pct.className   = m >= 0 ? 'text-success fw-bold' : 'text-danger fw-bold';
      abs.textContent = (p - c).toFixed(2);
      box.style.removeProperty('display');
    } else {
      box.style.display = 'none';
    }
  }

  precio.addEventListener('input', actualizar);
  coste.addEventListener('input',  actualizar);
  actualizar();
})();
</script>
{% endblock %}
