{% extends "base.html" %}
{% block title %}Nueva factura{% endblock %}
{% block page_title %}Nueva factura emitida{% endblock %}

{% block extra_head %}
<style>
  .lineas-table td { padding: 6px 4px; }
  .lineas-table input { padding: 4px 8px; font-size: .875rem; }
</style>
{% endblock %}

{% block content %}
<form method="post" id="formFactura" enctype="multipart/form-data">
<div class="row g-3">
  <!-- Cabecera -->
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-file-earmark-arrow-up me-2"></i>Datos de la factura</div>
      <div class="card-body p-4">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Número de factura *</label>
            <input type="text" name="numero" class="form-control" value="{{ siguiente }}" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Fecha *</label>
            <input type="date" name="fecha" class="form-control" value="{{ hoy }}" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Fecha de vencimiento</label>
            <input type="date" name="fecha_vencimiento" class="form-control" value="{{ venc }}">
          </div>
          <div class="col-12">
            <label class="form-label">Cliente</label>
            <select name="cliente_id" class="form-select">
              <option value="">— Sin cliente —</option>
              {% for c in clientes %}
              <option value="{{ c.id }}">{{ c.nombre }}</option>
              {% endfor %}
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- Líneas -->
    <div class="card mt-3">
      <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i>Líneas de factura</span>
        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addLinea()">
          <i class="bi bi-plus-lg"></i> Añadir línea
        </button>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table lineas-table mb-0" id="tablLineas">
            <thead>
              <tr>
                <th style="width:40%">Descripción</th>
                <th style="width:12%">Cant.</th>
                <th style="width:17%">Precio unit.</th>
                <th style="width:12%">Dto. %</th>
                <th style="width:14%" class="text-end">Subtotal</th>
                <th style="width:5%"></th>
              </tr>
            </thead>
            <tbody id="lineasBody">
              <tr class="linea-row">
                <td><input type="text" name="descripcion[]" class="form-control" placeholder="Descripción del servicio/producto"></td>
                <td><input type="number" name="cantidad[]" class="form-control linea-num" value="1" min="0" step="any"></td>
                <td><input type="number" name="precio_unitario[]" class="form-control linea-num" value="0" min="0" step="any"></td>
                <td><input type="number" name="descuento_pct[]" class="form-control linea-num" value="0" min="0" max="100" step="any"></td>
                <td class="text-end fw-semibold subtotal-cell align-middle">0.00 €</td>
                <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeLinea(this)"><i class="bi bi-x"></i></button></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Totales y opciones -->
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-calculator me-2"></i>Totales</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label">Moneda</label>
          <select name="moneda" id="moneda" class="form-select" onchange="toggleTasa()">
            {% for cod in ['EUR','USD','GBP','MXN','ARS','COP','CLP','PEN','BRL','JPY','CNY','CAD','CHF'] %}
            <option value="{{ cod }}">{{ cod }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="mb-3" id="div-tasa" style="display:none">
          <label class="form-label">Tasa de cambio (1 <span id="lbl-moneda-tasa">USD</span> = X €)</label>
          <div class="input-group">
            <input type="number" name="tasa_cambio_eur" id="tasa_cambio_eur"
                   class="form-control" value="1.0" step="0.0001" min="0.0001">
            <button type="button" class="btn btn-outline-secondary btn-sm" id="btnTasa"
                    onclick="obtenerTasa()" title="Obtener tasa actual">
              <i class="bi bi-arrow-repeat"></i>
            </button>
          </div>
          <div class="form-text">Equivalencia aproximada para contabilidad</div>
        </div>
        <div class="mb-3">
          <label class="form-label">IVA %</label>
          <select name="iva_pct" class="form-select" id="ivaPct" onchange="recalcTotales()">
            <option value="0">0% (Exento)</option>
            <option value="4">4%</option>
            <option value="10">10%</option>
            <option value="21" selected>21%</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">IRPF %</label>
          <select name="irpf_pct" class="form-select" id="irpfPct" onchange="recalcTotales()">
            <option value="0" selected>0%</option>
            <option value="7">7%</option>
            <option value="15">15%</option>
            <option value="19">19%</option>
          </select>
        </div>
        <hr>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">Base imponible</span>
          <span id="resBase" class="fw-semibold">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">IVA</span>
          <span id="resIva" class="fw-semibold">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">IRPF (−)</span>
          <span id="resIrpf" class="fw-semibold text-danger">0.00 €</span>
        </div>
        <hr>
        <div class="d-flex justify-content-between">
          <span class="fw-bold">Total</span>
          <span id="resTotal" class="fw-bold fs-5">0.00 €</span>
        </div>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-body">
        <label class="form-label">Notas</label>
        <textarea name="notas" class="form-control" rows="3" placeholder="Notas o condiciones..."></textarea>
        <div class="mt-3">
          <label class="form-label">Etiquetas</label>
          <input type="text" name="etiquetas" class="form-control" placeholder="Ej: urgente, cliente vip, pendiente revisión">
          <div class="form-text">Separa varias etiquetas con comas.</div>
        </div>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-body">
        <label class="form-label"><i class="bi bi-paperclip me-1"></i>Adjuntar factura</label>
        <input type="file" name="archivo_factura" class="form-control" accept=".pdf,.png,.jpg,.jpeg">
        <div class="form-text">Opcional — PDF o imagen de la factura.</div>
      </div>
    </div>

    <div class="d-grid gap-2 mt-3">
      <button type="submit" class="btn btn-primary">
        <i class="bi bi-check-lg me-1"></i>Crear factura
      </button>
      <a href="{{ url_for('facturas.emitidas') }}" class="btn btn-outline-secondary">Cancelar</a>
    </div>
  </div>
</div>
</form>
{% endblock %}

{% block extra_scripts %}
<script>
function addLinea() {
  const tbody = document.getElementById('lineasBody');
  const fila = tbody.querySelector('.linea-row').cloneNode(true);
  fila.querySelectorAll('input').forEach(i => { if (i.name !== 'descuento_pct[]') i.value = i.name === 'cantidad[]' ? 1 : 0; });
  fila.querySelector('.subtotal-cell').textContent = '0.00 €';
  tbody.appendChild(fila);
  fila.querySelectorAll('.linea-num').forEach(i => i.addEventListener('input', recalcTotales));
}

function removeLinea(btn) {
  const rows = document.querySelectorAll('.linea-row');
  if (rows.length > 1) { btn.closest('tr').remove(); recalcTotales(); }
}

function recalcTotales() {
  let base = 0;
  document.querySelectorAll('.linea-row').forEach(row => {
    const cant = parseFloat(row.querySelector('[name="cantidad[]"]').value) || 0;
    const precio = parseFloat(row.querySelector('[name="precio_unitario[]"]').value) || 0;
    const dto = parseFloat(row.querySelector('[name="descuento_pct[]"]').value) || 0;
    const sub = cant * precio * (1 - dto / 100);
    row.querySelector('.subtotal-cell').textContent = sub.toFixed(2) + ' €';
    base += sub;
  });
  const ivaPct = parseFloat(document.getElementById('ivaPct').value) || 0;
  const irpfPct = parseFloat(document.getElementById('irpfPct').value) || 0;
  const iva = base * ivaPct / 100;
  const irpf = base * irpfPct / 100;
  const total = base + iva - irpf;
  document.getElementById('resBase').textContent = base.toFixed(2) + ' €';
  document.getElementById('resIva').textContent = iva.toFixed(2) + ' €';
  document.getElementById('resIrpf').textContent = irpf.toFixed(2) + ' €';
  document.getElementById('resTotal').textContent = total.toFixed(2) + ' €';
}

document.querySelectorAll('.linea-num').forEach(i => i.addEventListener('input', recalcTotales));
recalcTotales();

function toggleTasa() {
  var m = document.getElementById('moneda').value;
  document.getElementById('div-tasa').style.display = (m && m !== 'EUR') ? '' : 'none';
  var lbl = document.getElementById('lbl-moneda-tasa');
  if (lbl) lbl.textContent = m || 'EUR';
}
toggleTasa();

// ── Catálogo autocomplete ────────────────────────────────────
(function() {
  var _dd = null, _timer = null;
  function hide() { if (_dd) { _dd.remove(); _dd = null; } }
  function show(inp, prods) {
    hide();
    if (!prods.length) return;
    var dd = document.createElement('div');
    dd.style.cssText = 'position:fixed;z-index:9999;background:#fff;border:1px solid #dee2e6;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.1);max-height:200px;overflow-y:auto;';
    prods.forEach(function(p) {
      var item = document.createElement('div');
      item.style.cssText = 'padding:8px 12px;cursor:pointer;font-size:.85rem;border-bottom:1px solid #f3f5fa;';
      var itemStrong = document.createElement('strong');
      itemStrong.textContent = p.nombre;
      var itemSpan = document.createElement('span');
      itemSpan.style.cssText = 'color:#6c757d;margin-left:8px';
      itemSpan.textContent = p.precio.toFixed(2) + ' € · IVA ' + p.iva_pct + '%';
      item.appendChild(itemStrong);
      item.appendChild(itemSpan);
      item.addEventListener('mouseover', function() { this.style.background = '#f0f5ff'; });
      item.addEventListener('mouseout',  function() { this.style.background = ''; });
      item.addEventListener('mousedown', function(e) {
        e.preventDefault();
        var tr = inp.closest('tr');
        inp.value = p.nombre;
        var prEl = tr.querySelector('[name="precio_unitario[]"]');
        if (prEl) { prEl.value = p.precio.toFixed(2); }
        hide();
        recalcTotales();
      });
      dd.appendChild(item);
    });
    var rect = inp.getBoundingClientRect();
    dd.style.left = rect.left + 'px';
    dd.style.top  = (rect.bottom + 2) + 'px';
    dd.style.width = Math.max(rect.width, 260) + 'px';
    document.body.appendChild(dd);
    _dd = dd;
  }
  document.addEventListener('input', function(e) {
    if (!e.target || e.target.name !== 'descripcion[]') return;
    clearTimeout(_timer);
    var q = e.target.value.trim();
    if (q.length < 1) { hide(); return; }
    var inp = e.target;
    _timer = setTimeout(function() {
      fetch('/catalogo/api/buscar?q=' + encodeURIComponent(q))
        .then(function(r) { return r.json(); })
        .then(function(data) { show(inp, data); })
        .catch(function() {});
    }, 220);
  });
  document.addEventListener('click', function(e) { if (_dd && !_dd.contains(e.target)) hide(); });
  document.addEventListener('keydown', function(e) { if (e.key === 'Escape') hide(); });
})();

async function obtenerTasa() {
  const moneda = document.getElementById('moneda').value;
  if (!moneda || moneda === 'EUR') return;
  const btn = document.getElementById('btnTasa');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
  try {
    const r = await fetch('https://api.frankfurter.app/latest?from=' + moneda + '&to=EUR');
    const data = await r.json();
    const tasa = data.rates && data.rates.EUR;
    if (tasa) {
      document.getElementById('tasa_cambio_eur').value = tasa.toFixed(4);
    } else {
      alert('No se pudo obtener la tasa para ' + moneda);
    }
  } catch(e) {
    alert('Error al consultar el tipo de cambio. Comprueba tu conexión.');
  } finally {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-arrow-repeat"></i>';
  }
}
</script>
{% endblock %}
