{% extends "base.html" %}
{% block title %}Asignar proveedores{% endblock %}
{% block page_title %}Revisar y archivar facturas{% endblock %}

{% block extra_head %}
<style>
  .factura-card {
    background: #fff;
    border-radius: 12px;
    border: 1px solid #e8eaed;
    padding: 20px 24px;
    margin-bottom: 16px;
    transition: box-shadow .15s;
  }
  .factura-card:hover { box-shadow: 0 2px 12px rgba(0,0,0,.08); }
  .file-icon-lg { font-size: 2.2rem; }
  .file-name { font-size: .85rem; font-weight: 600; word-break: break-all; color: #1a1d23; }

  .badge-extraido   { background: #e8f4fd; color: #1565c0; border: 1px solid #bbdefb; }
  .badge-match      { background: #e8f5e9; color: #1b5e20; border: 1px solid #c8e6c9; }
  .badge-nuevo      { background: #fff8e1; color: #e65100; border: 1px solid #ffe082; }
  .badge-manual     { background: #f3f3f3; color: #555;    border: 1px solid #ddd; }

  .prov-match-box {
    background: #e8f5e9;
    border: 1px solid #a5d6a7;
    border-radius: 8px;
    padding: 10px 14px;
    font-size: .88rem;
  }
  .prov-nuevo-box {
    background: #fffde7;
    border: 1px solid #ffe082;
    border-radius: 8px;
    padding: 12px 14px;
    font-size: .88rem;
  }
  .toggle-manual { font-size: .78rem; }
  .manual-override { display: none; }
  .dato-chip {
    display: inline-flex; align-items: center; gap: 5px;
    background: #f0f4ff; border-radius: 20px;
    padding: 2px 10px; font-size: .78rem; color: #3a5dc8;
    border: 1px solid #c7d5f5; margin: 2px;
  }
</style>
{% endblock %}

{% block content %}
<form method="post" id="formArchivar">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <p class="text-muted mb-0 small">
      <i class="bi bi-magic me-1"></i>
      Los datos se han extraído automáticamente. Revisa y corrige si es necesario.
    </p>
    <button type="submit" class="btn btn-primary">
      <i class="bi bi-archive me-1"></i>Archivar todas ({{ staged|length }})
    </button>
  </div>

  {% for item in staged %}
  {% set i = loop.index0 %}
  {% set e = item.extraido or {} %}
  {% set m = item.match %}

  <div class="factura-card">
    <!-- Header: file + badges -->
    <div class="d-flex align-items-start gap-3 mb-3">
      {% if item.original.lower().endswith('.pdf') %}
        <i class="bi bi-file-earmark-pdf file-icon-lg text-danger"></i>
      {% else %}
        <i class="bi bi-file-earmark-image file-icon-lg text-primary"></i>
      {% endif %}
      <div class="flex-grow-1">
        <div class="file-name mb-1">{{ item.original }}</div>
        <div>
          {% if m %}
            <span class="badge badge-match rounded-pill px-3 py-1">
              <i class="bi bi-check-circle-fill me-1"></i>Proveedor encontrado
            </span>
          {% elif e.get('nif') %}
            <span class="badge badge-nuevo rounded-pill px-3 py-1">
              <i class="bi bi-person-plus me-1"></i>Nuevo proveedor detectado
            </span>
          {% elif e %}
            <span class="badge badge-extraido rounded-pill px-3 py-1">
              <i class="bi bi-file-text me-1"></i>Datos extraídos
            </span>
          {% else %}
            <span class="badge badge-manual rounded-pill px-3 py-1">
              <i class="bi bi-pencil me-1"></i>Rellenar manualmente
            </span>
          {% endif %}

          {% if e.get('nif') %}
            <span class="dato-chip"><i class="bi bi-person-vcard"></i>{{ e.nif }}</span>
          {% endif %}
          {% if e.get('email') %}
            <span class="dato-chip"><i class="bi bi-envelope"></i>{{ e.email }}</span>
          {% endif %}
          {% if e.get('telefono') %}
            <span class="dato-chip"><i class="bi bi-telephone"></i>{{ e.telefono }}</span>
          {% endif %}
        </div>
      </div>
    </div>

    <div class="row g-3">

      <!-- PROVEEDOR -->
      <div class="col-lg-4">
        <label class="form-label small fw-semibold mb-1">Proveedor</label>

        {% if m %}
          <!-- Matched existing proveedor -->
          <div class="prov-match-box">
            <div class="d-flex align-items-center gap-2 mb-1">
              <i class="bi bi-building-check text-success"></i>
              <span class="fw-semibold">{{ m.nombre }}</span>
            </div>
            {% if e.get('nif') %}<div class="text-muted small">NIF: {{ e.nif }}</div>{% endif %}
          </div>
          <input type="hidden" name="proveedor_id_{{ i }}" value="{{ m.id }}">
          <input type="hidden" name="proveedor_nombre_{{ i }}" value="">
          <input type="hidden" name="proveedor_nif_{{ i }}" value="">
          <input type="hidden" name="proveedor_email_{{ i }}" value="">
          <input type="hidden" name="proveedor_tel_{{ i }}" value="">
          <div class="mt-2">
            <a href="#" class="toggle-manual text-muted"
               onclick="toggleOverride(event, 'ov_{{ i }}', {{ m.id }})">
              <i class="bi bi-pencil-square me-1"></i>Cambiar proveedor
            </a>
          </div>

        {% elif e.get('nif') or e.get('nombre') %}
          <!-- Extracted data, no DB match → new supplier -->
          <div class="prov-nuevo-box mb-2">
            <div class="small text-muted mb-2">
              <i class="bi bi-stars me-1"></i>Se creará automáticamente:
            </div>
            <input type="hidden" name="proveedor_id_{{ i }}" value="">
            <div class="mb-2">
              <label class="form-label small mb-1">Nombre *</label>
              <input type="text" name="proveedor_nombre_{{ i }}"
                     class="form-control form-control-sm"
                     value="{{ e.get('nombre', '') }}" required>
            </div>
            <div class="mb-2">
              <label class="form-label small mb-1">NIF/CIF</label>
              <input type="text" name="proveedor_nif_{{ i }}"
                     class="form-control form-control-sm"
                     value="{{ e.get('nif', '') }}">
            </div>
            <div class="row g-2">
              <div class="col-6">
                <label class="form-label small mb-1">Email</label>
                <input type="text" name="proveedor_email_{{ i }}"
                       class="form-control form-control-sm"
                       value="{{ e.get('email') or '' }}">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1">Teléfono</label>
                <input type="text" name="proveedor_tel_{{ i }}"
                       class="form-control form-control-sm"
                       value="{{ e.get('telefono') or '' }}">
              </div>
            </div>
          </div>
          <a href="#" class="toggle-manual text-muted"
             onclick="toggleOverride(event, 'ov_{{ i }}', null)">
            <i class="bi bi-arrow-left-right me-1"></i>Usar proveedor existente
          </a>

        {% else %}
          <!-- No extraction: manual -->
          <input type="hidden" name="proveedor_id_{{ i }}" id="pid_{{ i }}" value="">
          <input type="hidden" name="proveedor_nombre_{{ i }}" id="pnombre_{{ i }}" value="">
          <input type="hidden" name="proveedor_nif_{{ i }}" value="">
          <input type="hidden" name="proveedor_email_{{ i }}" value="">
          <input type="hidden" name="proveedor_tel_{{ i }}" value="">
          <select class="form-select form-select-sm"
                  onchange="selectProv(this, 'pid_{{ i }}', 'pnombre_{{ i }}', 'nuevo_{{ i }}')">
            <option value="">— Selecciona o escribe nuevo —</option>
            <option value="__nuevo__">+ Nuevo proveedor...</option>
            {% for p in proveedores %}
            <option value="{{ p.id }}">{{ p.nombre }}</option>
            {% endfor %}
          </select>
          <input type="text" id="nuevo_{{ i }}"
                 class="form-control form-control-sm mt-1"
                 style="display:none" placeholder="Nombre del nuevo proveedor"
                 oninput="document.getElementById('pnombre_{{ i }}').value=this.value">
        {% endif %}

        <!-- Override panel (shared by matched + extracted cases) -->
        <div class="manual-override mt-2" id="ov_{{ i }}">
          <select class="form-select form-select-sm" id="ov_sel_{{ i }}"
                  onchange="applyOverride(this, {{ i }})">
            <option value="">— Selecciona proveedor existente —</option>
            {% for p in proveedores %}
            <option value="{{ p.id }}">{{ p.nombre }}</option>
            {% endfor %}
          </select>
        </div>
      </div>

      <!-- NÚMERO -->
      <div class="col-lg-2">
        <label class="form-label small fw-semibold mb-1">Nº factura</label>
        <input type="text" name="numero_{{ i }}" class="form-control form-control-sm"
               value="{{ e.get('numero', '') }}" placeholder="Ej: F2026-001">
      </div>

      <!-- FECHA -->
      <div class="col-lg-2">
        <label class="form-label small fw-semibold mb-1">Fecha</label>
        <input type="date" name="fecha_{{ i }}" class="form-control form-control-sm"
               value="{{ e.get('fecha') or hoy }}">
      </div>

      <!-- IMPORTE -->
      <div class="col-lg-2">
        <label class="form-label small fw-semibold mb-1">Importe total €</label>
        <input type="text" name="importe_{{ i }}" class="form-control form-control-sm"
               value="{{ e.get('total', '') }}" placeholder="0.00">
      </div>

      <!-- CATEGORÍA -->
      <div class="col-lg-2">
        <label class="form-label small fw-semibold mb-1">Categoría</label>
        <select name="categoria_id_{{ i }}" class="form-select form-select-sm">
          <option value="">—</option>
          {% for c in categorias %}
          <option value="{{ c.id }}">{{ c.nombre }}</option>
          {% endfor %}
        </select>
      </div>

    </div>

    <!-- Artículos / líneas de producto -->
    <div class="mt-3">
      {% if item.lineas %}
      <div class="d-flex align-items-center gap-2 mb-2">
        <span class="badge rounded-pill px-3 py-1"
              style="background:#e8f5e9;color:#1b5e20;border:1px solid #c8e6c9">
          <i class="bi bi-magic me-1"></i>{{ item.lineas|length }} artículo(s) detectado(s) automáticamente
        </span>
        <button type="button" class="btn btn-sm btn-link text-muted p-0 toggle-manual"
                onclick="toggleLineas({{ i }})">
          <span id="btn_lineas_lbl_{{ i }}">Ocultar</span>
        </button>
      </div>
      {% else %}
      <button type="button" class="btn btn-sm btn-outline-secondary"
              onclick="toggleLineas({{ i }})">
        <i class="bi bi-list-ul me-1"></i>
        <span id="btn_lineas_lbl_{{ i }}">Desglosar artículos (opcional)</span>
      </button>
      {% endif %}

      <div id="lineas_panel_{{ i }}"
           style="display:{% if item.lineas %}block{% else %}none{% endif %}"
           class="mt-2">
        <div class="table-responsive">
          <table class="table table-sm mb-1" style="min-width:540px">
            <thead>
              <tr class="table-light">
                <th>Artículo / descripción</th>
                <th style="width:90px">Cant.</th>
                <th style="width:110px">P. unit. €</th>
                <th style="width:40px"></th>
              </tr>
            </thead>
            <tbody id="lineas_tbody_{{ i }}">
              {% for lin in item.lineas %}
              <tr>
                <td><input type="text" name="lineas_desc_{{ i }}[]"
                           class="form-control form-control-sm"
                           value="{{ lin.descripcion }}"></td>
                <td><input type="number" name="lineas_cant_{{ i }}[]"
                           class="form-control form-control-sm"
                           value="{{ lin.cantidad }}"
                           min="0.001" step="any"></td>
                <td><input type="number" name="lineas_precio_{{ i }}[]"
                           class="form-control form-control-sm"
                           value="{{ '%.2f'|format(lin.precio_unitario) }}"
                           min="0" step="0.01"></td>
                <td class="text-center">
                  <button type="button" class="btn btn-sm btn-outline-danger px-2"
                          onclick="this.closest('tr').remove()">
                    <i class="bi bi-x"></i>
                  </button>
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        <button type="button" class="btn btn-sm btn-outline-primary"
                onclick="addLinea({{ i }})">
          <i class="bi bi-plus me-1"></i>Añadir artículo
        </button>
        {% if not item.lineas %}
        <span class="text-muted small ms-2">
          Si no se añaden artículos, se creará una línea genérica con el importe total.
        </span>
        {% endif %}
      </div>
    </div>

  </div>
  {% endfor %}

  <div class="d-flex justify-content-between mt-2">
    <a href="{{ url_for('facturas.masivo_subir') }}" class="btn btn-outline-secondary">
      <i class="bi bi-arrow-left me-1"></i>Volver a subir
    </a>
    <button type="submit" class="btn btn-primary btn-lg">
      <i class="bi bi-archive me-1"></i>Archivar todas ({{ staged|length }})
    </button>
  </div>
</form>
{% endblock %}

{% block extra_scripts %}
<script>
function toggleOverride(evt, panelId, currentId) {
  evt.preventDefault();
  const panel = document.getElementById(panelId);
  panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}

function applyOverride(sel, i) {
  const pid = document.querySelector(`input[name="proveedor_id_${i}"]`);
  if (pid) pid.value = sel.value;
  const pnom = document.querySelector(`input[name="proveedor_nombre_${i}"]`);
  if (pnom && sel.value) pnom.value = '';
}

function selectProv(sel, pidId, pnomId, nuevoId) {
  const pidEl   = document.getElementById(pidId);
  const pnomEl  = document.getElementById(pnomId);
  const nuevoEl = document.getElementById(nuevoId);
  if (sel.value === '__nuevo__') {
    nuevoEl.style.display = 'block';
    nuevoEl.focus();
    pidEl.value  = '';
    pnomEl.value = '';
    sel.value    = '';
  } else {
    nuevoEl.style.display = 'none';
    pidEl.value  = sel.value;
    pnomEl.value = '';
  }
}

function toggleLineas(i) {
  const panel = document.getElementById(`lineas_panel_${i}`);
  const lbl   = document.getElementById(`btn_lineas_lbl_${i}`);
  const open  = panel.style.display === 'none';
  panel.style.display = open ? 'block' : 'none';
  if (lbl) {
    const isAuto = lbl.closest('.d-flex') !== null;
    lbl.textContent = open
      ? (isAuto ? 'Ocultar' : 'Ocultar artículos')
      : (isAuto ? 'Mostrar artículos' : 'Desglosar artículos (opcional)');
  }
  if (open && document.getElementById(`lineas_tbody_${i}`).children.length === 0) {
    addLinea(i);
  }
}

function addLinea(i) {
  const tbody = document.getElementById(`lineas_tbody_${i}`);
  const tr = document.createElement('tr');
  tr.innerHTML =
    `<td><input type="text" name="lineas_desc_${i}[]"
               class="form-control form-control-sm"
               placeholder="Ej: Pokemon Booster Pack"></td>` +
    `<td><input type="number" name="lineas_cant_${i}[]"
               class="form-control form-control-sm" value="1"
               min="0.001" step="any"></td>` +
    `<td><input type="number" name="lineas_precio_${i}[]"
               class="form-control form-control-sm" value="0"
               min="0" step="0.01"></td>` +
    `<td class="text-center">
       <button type="button" class="btn btn-sm btn-outline-danger px-2"
               onclick="this.closest('tr').remove()">
         <i class="bi bi-x"></i>
       </button>
     </td>`;
  tbody.appendChild(tr);
  tr.querySelector('input[type="text"]').focus();
}
</script>
{% endblock %}
