import { FormChangeTracker } from '../components/ConfirmExitModal.js';
import { navigationGuards } from '../router.js';
import { apiGet, apiPost } from '../services/apiClient.js';
import { icons } from '../services/icons.js';
import { showToast } from '../services/toast.js';
import { getPaymentTerms } from '../services/setup.js';
import { getInvoiceTemplates, getTemplateById } from '../services/invoices.js';

export function renderCreateInvoicePage() {
  const container = document.createElement('div');
  container.className = 'create-invoice-page page-enter';

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

  container.innerHTML = /*html*/`
    <div class="invoice-header-compact">
      <h1>Nueva Factura</h1>
      <div style="display:flex;gap:0.5rem;align-items:center;">
        <button type="button" class="btn-template" id="template-btn">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>
          Usar plantilla
        </button>
        <button class="btn-back" id="back-btn">← Volver</button>
      </div>
    </div>

    <!-- Panel de plantillas (oculto por defecto) -->
    <div id="template-panel" class="template-panel" style="display:none;">
      <div class="template-panel-header">
        <span>Seleccionar plantilla</span>
        <button type="button" id="template-panel-close" class="template-panel-close">×</button>
      </div>
      <div id="template-list" class="template-list">
        <p class="template-loading">Cargando plantillas...</p>
      </div>
    </div>

    <form class="invoice-form-compact" id="invoice-form">
      <div class="form-grid-compact">
        <div class="form-field-compact full-width">
          <label>Cliente</label>
          <select id="clientId" name="clientId" required disabled>
            <option value="">Cargando...</option>
          </select>
        </div>

        <div class="form-field-compact">
          <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>
          <div class="date-input-wrapper">
            <input type="date" id="date" name="date" min="2000-01-01" max="2100-12-31" />
            <button type="button" class="date-picker-btn" data-target="date" title="Seleccionar fecha">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
            </button>
          </div>
        </div>

        <div class="form-field-compact">
          <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>Vencimiento</label>
          <div class="date-input-wrapper">
            <input type="date" id="expireDate" name="expireDate" min="2000-01-01" max="2100-12-31" />
            <button type="button" class="date-picker-btn" data-target="expireDate" title="Seleccionar fecha">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
            </button>
          </div>
        </div>

        <div class="form-field-compact full-width">
          <label>Condiciones de pago</label>
          <select id="paymentTerms" name="paymentTerms">
            <option value="">Sin condiciones específicas</option>
          </select>
        </div>
      </div>

      <div class="notes-grid-compact">
        <div class="form-field-compact">
          <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 id="notePublic" name="notePublic" rows="2" placeholder="Visible para el cliente (opcional)"></textarea>
        </div>

        <div class="form-field-compact">
          <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 id="notePrivate" name="notePrivate" rows="2" placeholder="Interna (opcional)"></textarea>
        </div>
      </div>

      <div class="lines-section-compact">
        <div class="lines-header-compact">
          <h3>Líneas de Factura</h3>
          <button type="button" class="btn-add-compact" id="add-line-btn">+ Añadir</button>
        </div>
        
        <div class="lines-table-compact" id="invoice-lines-container"></div>
      </div>

      <div class="form-actions-compact">
        <button type="button" class="btn-cancel-compact" id="cancel-btn">Cancelar</button>
        <button type="submit" class="btn-submit-compact">Crear Factura</button>
      </div>
    </form>
  `;

  const clientSelect = container.querySelector('#clientId');

  async function loadClients() {
    try {
      const clients = await apiGet('/api/Clients?limit=1000');
      
      clientSelect.innerHTML = '<option value="">Seleccionar cliente...</option>';
      clients.forEach(client => {
        const option = document.createElement('option');
        option.value = client.id;
        option.textContent = client.name;
        clientSelect.appendChild(option);
      });

      clientSelect.disabled = false;
    } catch (error) {
      console.error('Error:', error);
      clientSelect.innerHTML = '<option value="">Error al cargar</option>';
    }
  }

  loadClients();

  const today = new Date().toISOString().split('T')[0];
  container.querySelector('#date').value = today;

  const expireDate = new Date();
  expireDate.setDate(expireDate.getDate() + 30);
  container.querySelector('#expireDate').value = expireDate.toISOString().split('T')[0];

  // Condiciones de pago — calcula vencimiento automáticamente al seleccionar
  async function loadPaymentTerms() {
    try {
      const terms = await getPaymentTerms();
      const select = container.querySelector('#paymentTerms');
      terms.forEach(t => {
        if (!t.label && !t.code) return;
        const opt = document.createElement('option');
        opt.value = t.nbjour ?? '';
        opt.textContent = t.label || t.code;
        select.appendChild(opt);
      });
    } catch { /* opcional — fallo silencioso */ }
  }
  loadPaymentTerms();

  // --- Plantillas ---
  let templatesCache = null;

  async function openTemplatePanel() {
    const panel = container.querySelector('#template-panel');
    const listEl = container.querySelector('#template-list');
    panel.style.display = 'block';

    if (templatesCache === null) {
      listEl.innerHTML = '<p class="template-loading">Cargando plantillas...</p>';
      try {
        templatesCache = await getInvoiceTemplates();
      } catch {
        listEl.innerHTML = '<p class="template-loading">Error al cargar plantillas.</p>';
        return;
      }
    }

    if (!templatesCache.length) {
      listEl.innerHTML = '<p class="template-loading">No hay plantillas disponibles.</p>';
      return;
    }

    listEl.innerHTML = templatesCache.map(t => `
      <button type="button" class="template-item" data-id="${t.id}">
        <span class="template-item-number">${t.number || `#${t.id}`}</span>
        <span class="template-item-client">${t.clientName || '—'}</span>
        <span class="template-item-total">${new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(t.total || 0)}</span>
      </button>
    `).join('');

    listEl.querySelectorAll('.template-item').forEach(btn => {
      btn.addEventListener('click', () => applyTemplate(parseInt(btn.dataset.id)));
    });
  }

  async function applyTemplate(id) {
    const panel = container.querySelector('#template-panel');
    const listEl = container.querySelector('#template-list');
    listEl.innerHTML = '<p class="template-loading">Cargando detalle...</p>';

    try {
      const detail = await getTemplateById(id);
      panel.style.display = 'none';

      // Pre-fill client
      if (detail.clientId) {
        const clientSelect = container.querySelector('#clientId');
        clientSelect.value = String(detail.clientId);
      }

      // Pre-fill notes
      if (detail.notePublic) container.querySelector('#notePublic').value = detail.notePublic;
      if (detail.notePrivate) container.querySelector('#notePrivate').value = detail.notePrivate;

      // Replace lines
      const linesContainer = container.querySelector('#invoice-lines-container');
      linesContainer.innerHTML = '';
      lineCounter = 0;

      const linesToAdd = detail.lines?.length ? detail.lines : [null];
      linesToAdd.forEach(line => {
        const lineDiv = createInvoiceLine();
        if (line) {
          lineDiv.querySelector('.line-desc-compact').value  = line.description || '';
          lineDiv.querySelector('.line-qty-compact').value   = line.quantity ?? 1;
          lineDiv.querySelector('.line-price-compact').value = line.unitPrice ?? 0;
          lineDiv.querySelector('.line-tax-compact').value   = line.taxRate ?? 21;
          lineDiv.querySelector('.line-total-compact').textContent =
            `${((line.quantity ?? 1) * (line.unitPrice ?? 0) * (1 + (line.taxRate ?? 21) / 100)).toFixed(2)} €`;
        }
        linesContainer.appendChild(lineDiv);
      });

      showToast('Plantilla aplicada', 'success');
    } catch {
      listEl.innerHTML = '<p class="template-loading">Error al cargar la plantilla.</p>';
    }
  }

  container.querySelector('#template-btn').addEventListener('click', openTemplatePanel);
  container.querySelector('#template-panel-close').addEventListener('click', () => {
    container.querySelector('#template-panel').style.display = 'none';
  });

  container.querySelector('#paymentTerms').addEventListener('change', (e) => {
    const days = parseInt(e.target.value);
    if (!days || days <= 0) return;
    const base = new Date(container.querySelector('#date').value || today);
    base.setDate(base.getDate() + days);
    container.querySelector('#expireDate').value = base.toISOString().split('T')[0];
  });

  // Si cambia la fecha base, recalcular vencimiento si hay condición seleccionada
  container.querySelector('#date').addEventListener('change', (e) => {
    const days = parseInt(container.querySelector('#paymentTerms').value);
    if (!days || days <= 0) return;
    const base = new Date(e.target.value);
    base.setDate(base.getDate() + days);
    container.querySelector('#expireDate').value = base.toISOString().split('T')[0];
  });

  // Event listeners para botones de calendario
  container.querySelectorAll('.date-picker-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const targetInput = container.querySelector(`#${btn.dataset.target}`);
      if (targetInput) targetInput.showPicker();
    });
  });

  let lineCounter = 0;

  function createInvoiceLine() {
    lineCounter++;
    const lineDiv = document.createElement('div');
    lineDiv.className = 'line-row-compact';

    lineDiv.innerHTML = /*html*/`
      <input type="text" class="line-desc-compact" required placeholder="Descripción" />
      <input type="number" class="line-qty-compact" required min="0.01" step="0.01" value="1" placeholder="Cant" />
      <input type="number" class="line-price-compact" required min="0" step="0.01" placeholder="Precio" />
      <input type="number" class="line-tax-compact" required min="0" max="100" step="0.01" value="21" placeholder="IVA %" />
      <div class="line-total-compact">0.00 €</div>
      <button type="button" class="btn-delete-compact" data-line-id="${lineCounter}">×</button>
    `;

    const descInput = lineDiv.querySelector('.line-desc-compact');
    const qtyInput = lineDiv.querySelector('.line-qty-compact');
    const priceInput = lineDiv.querySelector('.line-price-compact');
    const taxInput = lineDiv.querySelector('.line-tax-compact');
    const totalDiv = lineDiv.querySelector('.line-total-compact');

    function updateTotal() {
      const qty = parseFloat(qtyInput.value) || 0;
      const price = parseFloat(priceInput.value) || 0;
      const tax = parseFloat(taxInput.value) || 0;
      const subtotal = qty * price;
      const total = subtotal * (1 + tax / 100);
      totalDiv.textContent = `${total.toFixed(2)} €`;
    }

    qtyInput.addEventListener('input', updateTotal);
    priceInput.addEventListener('input', updateTotal);
    taxInput.addEventListener('input', updateTotal);

    lineDiv.querySelector('.btn-delete-compact').addEventListener('click', () => {
      lineDiv.remove();
    });

    return lineDiv;
  }

  const linesContainer = container.querySelector('#invoice-lines-container');
  linesContainer.appendChild(createInvoiceLine());
  linesContainer.appendChild(createInvoiceLine());

  container.querySelector('#add-line-btn').addEventListener('click', () => {
    linesContainer.appendChild(createInvoiceLine());
  });

  // Capturar estado inicial después de cargar clientes y crear líneas iniciales
  setTimeout(() => {
    changeTracker.captureInitialState(container);
    changeTracker.setupAutoTracking(container);
    
    // Registrar guard en el router - bloquea navegación si hay cambios
    navigationGuards.register(() => {
      if (savedSuccessfully) return false;
      changeTracker.checkForChanges(container);
      return changeTracker.hasChanges;
    });
  }, 500);

  // Interceptar beforeunload (cerrar pestaña/navegador)
  const handleBeforeUnload = (e) => {
    if (savedSuccessfully) return;
    
    changeTracker.checkForChanges(container);
    
    if (changeTracker.hasChanges) {
      e.preventDefault();
      e.returnValue = '';
      return '';
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  // Botón volver - el router se encarga del modal
  container.querySelector('#back-btn').addEventListener('click', () => {
    window.location.hash = '#invoices';
  });

  // Botón cancelar - el router se encarga del modal
  container.querySelector('#cancel-btn').addEventListener('click', () => {
    window.location.hash = '#invoices';
  });

  container.querySelector('#invoice-form').addEventListener('submit', async (e) => {
    e.preventDefault();

    const clientIdValue = parseInt(container.querySelector('#clientId').value);
    
    if (!clientIdValue || isNaN(clientIdValue) || clientIdValue < 1) {
      showToast('Selecciona un cliente', 'warning');
      return;
    }

    const lines = container.querySelectorAll('.line-row-compact');
    if (lines.length === 0) {
      showToast('Añade al menos una línea', 'warning');
      return;
    }

    // Validar fechas coherentes
    const dateValue = container.querySelector('#date').value;
    const expireDateValue = container.querySelector('#expireDate').value;

    function isValidDate(dateStr) {
      if (!dateStr) return false;
      const parts = dateStr.split('-');
      if (parts.length !== 3) return false;
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      if (year < 2000 || year > 2100) return false;
      if (month < 1 || month > 12) return false;
      if (day < 1 || day > 31) return false;
      const d = new Date(year, month - 1, day);
      return d.getFullYear() === year && d.getMonth() === month - 1 && d.getDate() === day;
    }

    if (!isValidDate(dateValue)) {
      showToast('La fecha de factura no es válida.', 'warning');
      return;
    }

    if (!isValidDate(expireDateValue)) {
      showToast('La fecha de vencimiento no es válida.', 'warning');
      return;
    }

    const dateObj = new Date(dateValue);
    const expireDateObj = new Date(expireDateValue);
    if (expireDateObj < dateObj) {
      showToast('La fecha de vencimiento no puede ser anterior a la de factura.', 'warning');
      return;
    }

    const formData = {
      clientId: clientIdValue,
      date: container.querySelector('#date').value + 'T00:00:00',
      expireDate: container.querySelector('#expireDate').value + 'T00:00:00',
      notePublic: container.querySelector('#notePublic').value || null,
      notePrivate: container.querySelector('#notePrivate').value || null,
      lines: []
    };

    let hasEmptyLine = false;
    lines.forEach(line => {
      const desc = line.querySelector('.line-desc-compact').value.trim();
      const qty = parseFloat(line.querySelector('.line-qty-compact').value);
      const price = parseFloat(line.querySelector('.line-price-compact').value);
      const tax = parseFloat(line.querySelector('.line-tax-compact').value);

      if (!desc || !qty || !price) {
        hasEmptyLine = true;
        return;
      }

      formData.lines.push({
        description: desc,
        quantity: qty,
        unitPrice: price,
        taxRate: tax
      });
    });

    if (hasEmptyLine) {
      showToast('Completa todos los campos de las líneas', 'warning');
      return;
    }

    try {
      const submitBtn = container.querySelector('.btn-submit-compact');
      submitBtn.disabled = true;
      submitBtn.textContent = 'Guardando...';

      const invoiceId = await apiPost('/api/Invoices', formData);
      
      // Marcar como guardado exitosamente para evitar el modal de confirmación
      savedSuccessfully = true;
      changeTracker.cleanup();
      navigationGuards.unregister();
      window.removeEventListener('beforeunload', handleBeforeUnload);
      
      showToast(`Factura creada (ID: ${invoiceId})`, 'success');
      window.location.hash = '#invoices';

    } catch (error) {
      console.error('Error:', error);
      showToast(error.message || 'Error al crear la factura', 'error');
      
      const submitBtn = container.querySelector('.btn-submit-compact');
      if (submitBtn) {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Crear Factura';
      }
    }
  });

  return container;
}
