import { getInvoiceById, updateInvoice, validateInvoice, addInvoiceLine, deleteInvoiceLine, updateInvoiceLine, addPayment, getPayments, downloadInvoicePdf } from '../services/invoices.js';
import { showConfirmExitModal, FormChangeTracker } from './ConfirmExitModal.js';
import { toast } from '../services/toast.js';
import { getPaymentTypes } from '../services/setup.js';
import { apiGet, apiRequest } from '../services/apiClient.js';

export function InvoiceModal(invoiceId, onClose, onUpdate) {
  const modal = document.createElement('div');
  modal.className = 'modal-overlay';

  let invoice = null;
  let payments = [];
  let paymentTypes = [];
  let bankAccounts = [];
  let documents = [];
  let isLoading = true;

  // Tracker de cambios
  const changeTracker = new FormChangeTracker();
  let savedSuccessfully = false;
  let activePreviewBlobUrl = null;

  // Formatear fecha para input type="date"
  const formatDateForInput = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
  };

  // Formatear fecha para mostrar
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES');
  };

  // Formatear tamaño de archivo
  const formatFileSize = (bytes) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // Formatear moneda
  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('es-ES', {
      style: 'currency',
      currency: 'EUR'
    }).format(amount || 0);
  };

  // Obtener texto de estado
  const getStatusText = (status) => {
    const statusTextMap = {
      'draft': 'Borrador',
      'validated': 'Pte. Pago',
      'paid': 'Pagada',
      'unpaid': 'Pte. Pago',
      'canceled': 'Cancelada'
    };
    return statusTextMap[status] || status;
  };

  // Renderizar contenido del modal
  const renderContent = () => {
    const modalContent = modal.querySelector('.modal-content');

    if (isLoading) {
      modalContent.innerHTML = `
        <div class="modal-header">
          <h2>Cargando...</h2>
          <button class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="loading">Cargando detalles de la factura...</div>
        </div>
      `;
      modalContent.querySelector('.btn-close')?.addEventListener('click', handleClose);
      return;
    }

    if (!invoice) {
      modalContent.innerHTML = `
        <div class="modal-header">
          <h2>Error</h2>
          <button class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="error">No se pudo cargar la factura</div>
        </div>
      `;
      modalContent.querySelector('.btn-close')?.addEventListener('click', handleClose);
      return;
    }

    const isDraft = invoice.status === 'draft';
    const canEdit = isDraft || invoice.status === 'validated' || invoice.status === 'unpaid';
    const canDownloadPdf = invoice.status === 'validated' || invoice.status === 'paid';

    modalContent.innerHTML = `
      <div class="modal-header">
        <div class="modal-title">
          <h2>${invoice.number || 'Nueva Factura'}</h2>
          <span class="status-badge status-${invoice.status}">
            ${getStatusText(invoice.status)}
          </span>
        </div>
        <button class="btn-close">×</button>
      </div>

      <div class="modal-body">
        <form id="invoice-form">
          <!-- Información básica -->
          <div class="form-section">
            <h3>Información de la Factura</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label>Número de Factura</label>
                <input 
                  type="text" 
                  name="number" 
                  value="${invoice.number || ''}"
                  disabled
                />
              </div>
              
              <div class="form-group">
                <label><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 4px;"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>Fecha</label>
                <input 
                  type="date" 
                  name="date" 
                  value="${formatDateForInput(invoice.date)}"
                  disabled
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 4px;"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>Fecha de Vencimiento</label>
                <input 
                  type="date" 
                  name="expireDate" 
                  value="${formatDateForInput(invoice.expireDate)}"
                  ${!canEdit ? 'disabled' : ''}
                />
              </div>
              
              <div class="form-group">
                <label>Cliente</label>
                <input
                  type="text"
                  name="clientId"
                  value="${invoice.clientName || invoice.clientId || ''}"
                  disabled
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 4px;"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>Nota Pública</label>
                <textarea name="note_public" rows="3" placeholder="Visible para el cliente" ${!canEdit ? 'disabled' : ''}>${invoice.notePublic || ''}</textarea>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 4px;"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>Nota Privada</label>
                <textarea name="note_private" rows="3" placeholder="Solo uso interno" ${!canEdit ? 'disabled' : ''}>${invoice.notePrivate || ''}</textarea>
              </div>
            </div>
          </div>

          <!-- Líneas de factura -->
          <div class="form-section">
            <div class="section-header">
              <h3>Líneas de Factura</h3>
              ${isDraft ? '<button type="button" class="btn-add-line btn-small">+ Añadir Línea</button>' : ''}
            </div>

            ${isDraft ? `
            <div class="add-line-form" style="display: none;">
              <div class="form-row">
                <div class="form-group full-width">
                  <label>Descripción</label>
                  <input type="text" id="line-description" placeholder="Descripción del producto/servicio" />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Cantidad</label>
                  <input type="number" id="line-quantity" value="1" min="0.01" step="0.01" />
                </div>
                <div class="form-group">
                  <label>Precio Unitario (€)</label>
                  <input type="number" id="line-price" value="0" min="0" step="0.01" />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>IVA (%)</label>
                  <input type="number" id="line-tax" value="21" min="0" max="100" step="0.01" />
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end; gap: 0.5rem;">
                  <button type="button" class="btn-save-line btn-small btn-success">Guardar Línea</button>
                  <button type="button" class="btn-cancel-line btn-small btn-cancel">Cancelar</button>
                </div>
              </div>
            </div>
            ` : ''}

            <div class="invoice-lines">
              <table class="lines-table">
                <thead>
                  <tr>
                    <th>Descripción</th>
                    <th>Cantidad</th>
                    <th>Precio Unitario</th>
                    <th>IVA %</th>
                    <th>Total</th>
                    ${isDraft ? '<th class="line-actions-col"></th>' : ''}
                  </tr>
                </thead>
                <tbody>
                  ${invoice.lines && invoice.lines.length > 0
        ? invoice.lines.map(line => `
                      <tr data-line-id="${line.id}">
                        <td>${line.description || ''}</td>
                        <td>${line.quantity || 0}</td>
                        <td>${formatCurrency(line.unitPrice)}</td>
                        <td>${line.taxRate || 0}%</td>
                        <td>${formatCurrency(line.total)}</td>
                        ${isDraft ? `
                          <td class="line-actions">
                            <button type="button" class="btn-edit-line" data-line-id="${line.id}" title="Editar línea">
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                            </button>
                            <button type="button" class="btn-delete-line" data-line-id="${line.id}" title="Eliminar línea">
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="3 6 5 6 21 6"/>
                                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                              </svg>
                            </button>
                          </td>
                        ` : ''}
                      </tr>
                    `).join('')
        : `<tr><td colspan="${isDraft ? 6 : 5}" class="no-lines">No hay líneas en esta factura</td></tr>`
      }
                </tbody>
              </table>
            </div>

            <!-- Totales -->
            <div class="invoice-totals">
              ${invoice.totalHt != null ? `
              <div class="total-row subtotal">
                <span>Base imponible:</span>
                <strong>${formatCurrency(invoice.totalHt)}</strong>
              </div>` : ''}
              ${invoice.totalTax != null ? `
              <div class="total-row subtotal">
                <span>IVA:</span>
                <strong>${formatCurrency(invoice.totalTax)}</strong>
              </div>` : ''}
              <div class="total-row">
                <span>Total:</span>
                <strong class="amount-positive">${formatCurrency(invoice.total)}</strong>
              </div>
              ${invoice.status === 'paid' ? `
              <div class="total-row total-row--highlight total-row--highlight-paid">
                <span>Pagado:</span>
                <strong>${formatCurrency(invoice.total || 0)}</strong>
              </div>` : `
              <div class="total-row total-row--highlight total-row--highlight-pending">
                <span>Pendiente:</span>
                <strong>${formatCurrency(Math.max(0, invoice.remainToPay || 0))}</strong>
              </div>`}
            </div>
          </div>

          ${payments.length > 0 ? `
          <!-- Historial de pagos -->
          <div class="form-section payments-history-section">
            <h3>Historial de Pagos</h3>
            <table class="payments-history-table">
              <thead>
                <tr>
                  <th>Fecha</th>
                  <th>Referencia</th>
                  <th>Tipo</th>
                  <th>Nº Transacción</th>
                  <th>Importe</th>
                </tr>
              </thead>
              <tbody>
                ${payments.map(p => `
                  <tr>
                    <td>${formatDate(p.paymentDate)}</td>
                    <td class="payment-ref-cell">${p.ref || '—'}</td>
                    <td>${p.type ? `<span class="payment-type-pill">${p.type}</span>` : '—'}</td>
                    <td class="payment-ref-cell">${p.transactionNum || '—'}</td>
                    <td><span class="payment-amount-cell">${formatCurrency(p.amount)}</span></td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
          ` : ''}

          <!-- Documentos adjuntos -->
          <div class="form-section documents-section">
            <h3>Documentos</h3>
            ${documents.length === 0
              ? '<p class="no-documents">No hay documentos adjuntos a esta factura.</p>'
              : `<ul class="documents-list">
                  ${documents.map(doc => `
                    <li class="document-item">
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="doc-icon"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                      <span class="document-name">${doc.name}</span>
                      <span class="document-size">${formatFileSize(doc.size)}</span>
                      <button type="button" class="btn-download-doc" data-path="${encodeURIComponent(doc.relativePath || doc.name)}" data-name="${doc.name}" title="Descargar">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                        Descargar
                      </button>
                    </li>
                  `).join('')}
                </ul>`
            }
          </div>

          ${(invoice.status === 'validated' || invoice.status === 'unpaid') && invoice.remainToPay > 0 ? `
          <!-- Sección de pago -->
          <div class="form-section payment-section">
            <h3>Registrar Pago</h3>
            <div class="payment-form" id="payment-form">
              <div class="form-row">
                <div class="form-group">
                  <label>Cantidad a pagar (€)</label>
                  <input type="number" id="payment-amount"
                    min="0" max="${invoice.remainToPay}" step="0.01"
                    placeholder="Dejar vacío o 0 = pago total (${invoice.remainToPay?.toFixed(2)} €)" />
                  <small class="payment-hint">Máximo: ${formatCurrency(invoice.remainToPay)}. Vacío o 0 = pago completo.</small>
                </div>
                <div class="form-group">
                  <label>Fecha de pago</label>
                  <input type="date" id="payment-date" value="${new Date().toISOString().split('T')[0]}" />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Método de pago</label>
                  <select id="payment-method">
                    ${paymentTypes.length
                      ? paymentTypes.map(t => `<option value="${t.id}">${t.label || t.code}</option>`).join('')
                      : '<option value="4">Tarjeta bancaria</option>'}
                  </select>
                </div>
                <div class="form-group">
                  <label>Cuenta bancaria</label>
                  <select id="payment-account">
                    ${bankAccounts.length
                      ? bankAccounts.map(a => `<option value="${a.id}">${a.label}${a.iban ? ' · ' + a.iban.slice(-4) : ''}</option>`).join('')
                      : '<option value="1">Cuenta principal</option>'}
                  </select>
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Nº Referencia (opcional)</label>
                  <input type="text" id="payment-ref" placeholder="Nº de referencia del pago" />
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end;">
                  <button type="button" class="btn-pay btn-success" id="btn-pay">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                    Registrar Pago
                  </button>
                </div>
              </div>
            </div>
          </div>
          ` : ''}
        </form>
      </div>

      <div class="modal-footer">
        <div class="footer-actions-left">
          ${canDownloadPdf ? '<button type="button" class="btn-preview-invoice btn-cancel"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>Vista previa</button>' : ''}
          ${canDownloadPdf ? '<button type="button" class="btn-download-invoice btn-primary"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>Descargar factura</button>' : ''}
          ${isDraft ? '<button type="button" class="btn-validate btn-success"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><polyline points="20 6 9 17 4 12"/></svg>Validar Factura</button>' : ''}
        </div>
        <div class="footer-actions-right">
          <button type="button" class="btn-cancel-modal">Cancelar</button>
          ${canEdit ? '<button type="button" class="btn-save btn-primary">Guardar Cambios</button>' : ''}
        </div>
      </div>
    `;

    attachEventListeners();

    // Capturar estado inicial después de renderizar
    setTimeout(() => {
      const modalContent = modal.querySelector('.modal-content');
      if (modalContent && !isLoading) {
        changeTracker.captureInitialState(modalContent);
        changeTracker.setupAutoTracking(modalContent);
      }
    }, 100);
  };

  // Adjuntar event listeners
  const attachEventListeners = () => {
    // Botón cerrar (X) - muestra modal si hay cambios
    const closeBtn = modal.querySelector('.btn-close');
    closeBtn?.addEventListener('click', handleClose);

    // Botón cancelar modal - muestra modal si hay cambios
    const cancelBtn = modal.querySelector('.btn-cancel-modal');
    cancelBtn?.addEventListener('click', handleClose);

    // Botón guardar
    const saveBtn = modal.querySelector('.btn-save');
    saveBtn?.addEventListener('click', handleSave);

    // Botón validar
    const validateBtn = modal.querySelector('.btn-validate');
    validateBtn?.addEventListener('click', handleValidate);

    // Botón vista previa de factura PDF
    const previewBtn = modal.querySelector('.btn-preview-invoice');
    previewBtn?.addEventListener('click', handlePreviewPdf);

    // Botón descargar factura PDF
    const downloadBtn = modal.querySelector('.btn-download-invoice');
    downloadBtn?.addEventListener('click', handleDownloadPdf);

    // Botón añadir línea
    const addLineBtn = modal.querySelector('.btn-add-line');
    addLineBtn?.addEventListener('click', toggleAddLineForm);

    // Botón guardar línea
    const saveLineBtn = modal.querySelector('.btn-save-line');
    saveLineBtn?.addEventListener('click', handleSaveLine);

    // Botón cancelar línea
    const cancelLineBtn = modal.querySelector('.btn-cancel-line');
    cancelLineBtn?.addEventListener('click', () => {
      const form = modal.querySelector('.add-line-form');
      if (form) form.style.display = 'none';
    });

    // Botones editar línea
    modal.querySelectorAll('.btn-edit-line').forEach(btn => {
      btn.addEventListener('click', () => handleEditLine(btn.dataset.lineId));
    });

    // Botones eliminar línea
    modal.querySelectorAll('.btn-delete-line').forEach(btn => {
      btn.addEventListener('click', () => handleDeleteLine(parseInt(btn.dataset.lineId)));
    });

    // Botones descargar documento
    modal.querySelectorAll('.btn-download-doc').forEach(btn => {
      btn.addEventListener('click', () => handleDocumentDownload(btn.dataset.path, btn.dataset.name));
    });

    // Botón registrar pago
    const payBtn = modal.querySelector('#btn-pay');
    payBtn?.addEventListener('click', handlePayment);

    // Click fuera del modal - muestra modal si hay cambios
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        handleClose();
      }
    });
  };

  // Manejar cierre
  const handleClose = async () => {
    // Si ya se guardó exitosamente, cerrar directamente
    if (savedSuccessfully) {
      changeTracker.cleanup();
      modal.remove();
      if (onClose) onClose();
      return;
    }

    // Verificar si hay cambios sin guardar
    const modalContent = modal.querySelector('.modal-content');
    if (modalContent) {
      changeTracker.checkForChanges(modalContent);
    }

    if (changeTracker.hasChanges) {
      // Mostrar modal de confirmación
      const confirmed = await showConfirmExitModal({
        title: 'Cambios sin guardar',
        message: 'Tienes cambios sin guardar en la factura. ¿Seguro que quieres cerrar?',
        confirmText: 'Cerrar sin guardar',
        cancelText: 'Seguir editando'
      });

      if (!confirmed) {
        return; // No cerrar el modal
      }
    }

    if (activePreviewBlobUrl) {
      URL.revokeObjectURL(activePreviewBlobUrl);
      activePreviewBlobUrl = null;
    }

    changeTracker.cleanup();
    modal.remove();
    if (onClose) onClose();
  };

  // Manejar guardado
  const handleSave = async () => {
    const form = modal.querySelector('#invoice-form');
    const formData = new FormData(form);

    // La API espera camelCase en el PUT (notePublic/notePrivate)
    const data = {
      number: formData.get('number') || undefined,
      expireDate: formData.get('expireDate') || undefined,
      notePublic: formData.get('note_public') || undefined,
      notePrivate: formData.get('note_private') || undefined
    };

    // Filtrar valores undefined
    Object.keys(data).forEach(key => {
      if (data[key] === undefined || data[key] === '') {
        delete data[key];
      }
    });

    try {
      const saveBtn = modal.querySelector('.btn-save');
      saveBtn.disabled = true;
      saveBtn.textContent = 'Guardando...';

      await updateInvoice(invoiceId, data);

      // Marcar como guardado exitosamente
      savedSuccessfully = true;
      changeTracker.markAsSaved();

      toast.success('Factura actualizada correctamente');
      if (onUpdate) onUpdate();
      handleClose();
    } catch (error) {
      console.error('Error al guardar:', error);
      toast.error('Error al guardar la factura: ' + error.message);
    } finally {
      const saveBtn = modal.querySelector('.btn-save');
      if (saveBtn) {
        saveBtn.disabled = false;
        saveBtn.textContent = 'Guardar Cambios';
      }
    }
  };

  // Manejar validación
  const handleValidate = async () => {
    const ok = await showConfirmExitModal({
      title: 'Validar factura',
      message: '¿Seguro que quieres validar esta factura? No podrás editarla completamente después.',
      confirmText: 'Validar',
      cancelText: 'Cancelar'
    });
    if (!ok) return;

    try {
      const validateBtn = modal.querySelector('.btn-validate');
      validateBtn.disabled = true;
      validateBtn.textContent = 'Validando...';

      await validateInvoice(invoiceId);

      // Marcar como guardado para no mostrar el modal de confirmación
      savedSuccessfully = true;
      changeTracker.markAsSaved();

      toast.success('Factura validada correctamente');
      if (onUpdate) onUpdate();

      // Recargar la factura para mostrar el nuevo estado
      await loadInvoice();

      // Recapturar estado inicial después de recargar
      savedSuccessfully = false;
    } catch (error) {
      console.error('Error al validar:', error);
      toast.error('Error al validar la factura: ' + error.message);

      const validateBtn = modal.querySelector('.btn-validate');
      if (validateBtn) {
        validateBtn.disabled = false;
        validateBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><polyline points="20 6 9 17 4 12"/></svg>Validar Factura';
      }
    }
  };

  // Manejar descarga del PDF
  const handleDownloadPdf = async () => {
    if (!invoice?.number) {
      toast.warning('No se puede descargar la factura porque no tiene número.');
      return;
    }

    const downloadBtn = modal.querySelector('.btn-download-invoice');
    const originalHtml = downloadBtn?.innerHTML;

    try {
      if (downloadBtn) {
        downloadBtn.disabled = true;
        downloadBtn.textContent = 'Descargando...';
      }

      const pdfBlob = await downloadInvoicePdf(invoice.number);
      const blobUrl = URL.createObjectURL(pdfBlob);
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = `Factura-${invoice.number}.pdf`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(blobUrl);
    } catch (error) {
      console.error('Error al descargar factura:', error);
      toast.error('Error al descargar la factura: ' + error.message);
    } finally {
      if (downloadBtn) {
        downloadBtn.disabled = false;
        downloadBtn.innerHTML = originalHtml;
      }
    }
  };

  // Manejar vista previa del PDF
  const handlePreviewPdf = async () => {
    if (!invoice?.number) {
      toast.warning('No se puede previsualizar la factura porque no tiene número.');
      return;
    }

    const previewBtn = modal.querySelector('.btn-preview-invoice');
    const originalHtml = previewBtn?.innerHTML;
    const previewWindow = window.open('', '_blank');

    if (!previewWindow) {
      toast.warning('El navegador bloqueó la ventana emergente. Permite popups para ver la vista previa.');
      return;
    }

    previewWindow.opener = null;
    previewWindow.document.title = 'Vista previa factura';

    try {
      if (previewBtn) {
        previewBtn.disabled = true;
        previewBtn.textContent = 'Abriendo...';
      }

      const pdfBlob = await downloadInvoicePdf(invoice.number);

      if (activePreviewBlobUrl) {
        URL.revokeObjectURL(activePreviewBlobUrl);
      }

      activePreviewBlobUrl = URL.createObjectURL(pdfBlob);
      previewWindow.location.href = activePreviewBlobUrl;
    } catch (error) {
      console.error('Error al previsualizar factura:', error);
      previewWindow.close();
      toast.error('Error al abrir la vista previa: ' + error.message);
    } finally {
      if (previewBtn) {
        previewBtn.disabled = false;
        previewBtn.innerHTML = originalHtml;
      }
    }
  };

  // Mostrar/ocultar formulario de añadir línea
  const toggleAddLineForm = () => {
    const form = modal.querySelector('.add-line-form');
    if (form) {
      const isVisible = form.style.display !== 'none';
      form.style.display = isVisible ? 'none' : 'block';

      if (!isVisible) {
        // Limpiar campos
        modal.querySelector('#line-description').value = '';
        modal.querySelector('#line-quantity').value = '1';
        modal.querySelector('#line-price').value = '0';
        modal.querySelector('#line-tax').value = '21';
      }
    }
  };

  // Guardar nueva línea
  const handleSaveLine = async () => {
    const description = modal.querySelector('#line-description').value.trim();
    const quantity = parseFloat(modal.querySelector('#line-quantity').value);
    const unitPrice = parseFloat(modal.querySelector('#line-price').value);
    const taxRate = parseFloat(modal.querySelector('#line-tax').value);

    if (!description) {
      toast.warning('La descripción es obligatoria');
      return;
    }

    if (!quantity || quantity <= 0) {
      toast.warning('La cantidad debe ser mayor que 0');
      return;
    }

    if (unitPrice < 0) {
      toast.warning('El precio no puede ser negativo');
      return;
    }

    if (taxRate < 0 || taxRate > 100) {
      toast.warning('El IVA debe estar entre 0 y 100');
      return;
    }

    try {
      const saveBtn = modal.querySelector('.btn-save-line');
      saveBtn.disabled = true;
      saveBtn.textContent = 'Guardando...';

      await addInvoiceLine(invoiceId, {
        description,
        quantity,
        unitPrice,
        taxRate
      });

      toast.success('Línea añadida correctamente');
      toggleAddLineForm();

      // Recargar y recapturar estado inicial
      await loadInvoice();
      changeTracker.markAsSaved();
    } catch (error) {
      console.error('Error al añadir línea:', error);
      toast.error('Error al añadir línea: ' + error.message);
    } finally {
      const saveBtn = modal.querySelector('.btn-save-line');
      if (saveBtn) {
        saveBtn.disabled = false;
        saveBtn.textContent = 'Guardar Línea';
      }
    }
  };

  // Editar línea de factura inline
  const handleEditLine = (lineId) => {
    const line = invoice.lines?.find(l => String(l.id) === String(lineId));
    if (!line) return;
    const row = modal.querySelector(`tr[data-line-id="${lineId}"]`);
    if (!row) return;

    row.innerHTML = `
      <td><input class="line-edit-input line-edit-desc" type="text" value="${(line.description || '').replace(/"/g, '&quot;')}" /></td>
      <td><input class="line-edit-input line-edit-qty"  type="number" value="${line.quantity  ?? 1}"  min="0.01" step="0.01" style="width:70px"/></td>
      <td><input class="line-edit-input line-edit-price" type="number" value="${line.unitPrice ?? 0}"  min="0"    step="0.01" style="width:90px"/></td>
      <td><input class="line-edit-input line-edit-tax"  type="number" value="${line.taxRate   ?? 21}" min="0" max="100" step="0.01" style="width:60px"/></td>
      <td>—</td>
      <td class="line-actions">
        <button type="button" class="btn-save-line-edit btn-small btn-success" title="Guardar">✓</button>
        <button type="button" class="btn-cancel-line-edit btn-small" title="Cancelar">✕</button>
      </td>
    `;

    row.querySelector('.btn-save-line-edit').addEventListener('click',  () => saveLineEdit(lineId, row));
    row.querySelector('.btn-cancel-line-edit').addEventListener('click', () => loadInvoice());
    row.querySelector('.line-edit-desc').focus();
  };

  const saveLineEdit = async (lineId, row) => {
    const description = row.querySelector('.line-edit-desc').value.trim();
    const quantity    = parseFloat(row.querySelector('.line-edit-qty').value);
    const unitPrice   = parseFloat(row.querySelector('.line-edit-price').value);
    const taxRate     = parseFloat(row.querySelector('.line-edit-tax').value);

    if (!description) { toast.warning('La descripción es obligatoria'); return; }
    if (!quantity || quantity <= 0) { toast.warning('La cantidad debe ser mayor que 0'); return; }

    const saveBtn = row.querySelector('.btn-save-line-edit');
    saveBtn.disabled = true;
    saveBtn.textContent = '…';

    try {
      await updateInvoiceLine(invoiceId, lineId, { description, quantity, unitPrice, taxRate });
      toast.success('Línea actualizada');
      if (onUpdate) onUpdate();
      await loadInvoice();
      changeTracker.markAsSaved();
    } catch (error) {
      toast.error('Error al actualizar línea: ' + error.message);
      saveBtn.disabled = false;
      saveBtn.textContent = '✓';
    }
  };

  // Eliminar línea de factura
  const handleDeleteLine = async (lineId) => {
    const ok = await showConfirmExitModal({
      title: 'Eliminar línea',
      message: '¿Seguro que quieres eliminar esta línea de la factura?',
      confirmText: 'Eliminar',
      cancelText: 'Cancelar'
    });
    if (!ok) return;

    try {
      // Deshabilitar el botón mientras se elimina
      const btn = modal.querySelector(`.btn-delete-line[data-line-id="${lineId}"]`);
      if (btn) {
        btn.disabled = true;
        btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="spin"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>';
      }

      await deleteInvoiceLine(invoiceId, lineId);

      if (onUpdate) onUpdate();
      await loadInvoice();
      changeTracker.markAsSaved();
    } catch (error) {
      console.error('Error al eliminar línea:', error);
      toast.error('Error al eliminar línea: ' + error.message);

      const btn = modal.querySelector(`.btn-delete-line[data-line-id="${lineId}"]`);
      if (btn) {
        btn.disabled = false;
        btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>';
      }
    }
  };

  // Manejar pago de factura
  const handlePayment = async () => {
    const amountInput = modal.querySelector('#payment-amount');
    const dateInput = modal.querySelector('#payment-date');
    const refInput = modal.querySelector('#payment-ref');

    if (!amountInput || !dateInput) return;

    const rawAmount = parseFloat(amountInput.value);
    const remainToPay = invoice.remainToPay;

    // Si vacío o 0, pago total (enviar null)
    let amount = null;
    if (!isNaN(rawAmount) && rawAmount > 0) {
      if (rawAmount > remainToPay) {
        toast.warning(`La cantidad no puede superar el pendiente de pago (${remainToPay.toFixed(2)} €)`);
        return;
      }
      amount = rawAmount;
    }

    const paymentDate = dateInput.value;
    if (!paymentDate) {
      toast.warning('La fecha de pago es obligatoria');
      return;
    }

    const paymentRef = refInput?.value?.trim() || undefined;
    const paymentModeId = parseInt(modal.querySelector('#payment-method')?.value) || 4;
    const accountId    = parseInt(modal.querySelector('#payment-account')?.value) || 1;

    try {
      const payBtn = modal.querySelector('#btn-pay');
      payBtn.disabled = true;
      payBtn.textContent = 'Procesando...';

      await addPayment(invoiceId, {
        amount: amount,
        paymentDate: paymentDate,
        paymentModeId,
        closePaidInvoices: "yes",
        accountId,
        numPayment: paymentRef
      });

      savedSuccessfully = true;
      changeTracker.markAsSaved();

      const displayAmount = amount ? `${amount.toFixed(2)} €` : `${remainToPay.toFixed(2)} € (total)`;
      toast.success(`Pago de ${displayAmount} registrado correctamente`);

      if (onUpdate) onUpdate();
      await loadInvoice();
      savedSuccessfully = false;
    } catch (error) {
      console.error('Error al registrar pago:', error);
      toast.error('Error al registrar el pago: ' + error.message);
    } finally {
      const payBtn = modal.querySelector('#btn-pay');
      if (payBtn) {
        payBtn.disabled = false;
        payBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;"><path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>Registrar Pago';
      }
    }
  };

  // Descargar documento adjunto
  const handleDocumentDownload = async (encodedPath, name) => {
    try {
      const response = await apiRequest(
        `/api/Document/download?modulePart=invoice&file=${encodedPath}`,
        { method: 'GET', responseType: 'raw' }
      );
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (err) {
      toast.error('Error al descargar documento: ' + err.message);
    }
  };

  // Cargar factura + datos auxiliares en paralelo
  const loadInvoice = async () => {
    try {
      isLoading = true;
      renderContent();

      // Load invoice first so we have invoice.number for the documents endpoint
      invoice = await getInvoiceById(invoiceId).catch(() => null);

      // Resolve client name if BFF didn't return it
      if (invoice && invoice.clientId && !invoice.clientName) {
        try {
          const clients = await apiGet(`/api/Clients?limit=500`);
          const list = Array.isArray(clients) ? clients : clients.data || [];
          const match = list.find(c => c.id === invoice.clientId);
          if (match) invoice.clientName = match.name || match.fullName || match.label;
        } catch { /* best-effort */ }
      }

      const [paymentsData, typesData, accountsData, documentsData] = await Promise.allSettled([
        getPayments(invoiceId),
        getPaymentTypes(),
        apiGet('/api/Bank/accounts'),
        invoice?.id
          ? apiGet(`/api/Document/list?modulePart=invoice&id=${invoice.id}`)
          : Promise.resolve([]),
      ]);

      payments     = paymentsData.status === 'fulfilled'   ? paymentsData.value   : [];
      paymentTypes = typesData.status === 'fulfilled'      ? typesData.value      : [];
      bankAccounts = accountsData.status === 'fulfilled'   ? accountsData.value   : [];
      documents    = documentsData.status === 'fulfilled'  ? (documentsData.value ?? []) : [];

      isLoading = false;
      renderContent();
    } catch (error) {
      console.error('Error al cargar factura:', error);
      isLoading = false;
      invoice = null;
      renderContent();
    }
  };

  // Inicializar modal
  modal.innerHTML = `
    <div class="modal-content invoice-modal">
    </div>
  `;

  // Escape key closes modal
  const handleEscapeKey = (e) => {
    if (e.key !== 'Escape') return;
    if (!modal.isConnected) {
      document.removeEventListener('keydown', handleEscapeKey);
      return;
    }
    handleClose();
  };
  document.addEventListener('keydown', handleEscapeKey);

  // Cargar factura
  loadInvoice();

  return modal;
}
