import { icons } from '../services/icons.js';
import { getContacts, getContactById, createContact, updateContact, deleteContact } from '../services/contacts.js';
import { showToast } from '../services/toast.js';
import { apiGet } from '../services/apiClient.js';

export function renderContactsPage() {
  const container = document.createElement('div');
  container.className = 'facturas-page page-enter';

  let allContacts = [];
  let filteredContacts = [];
  let searchTerm = '';
  let clients = [];

  const escHtml = (str) => {
    if (str == null) return '';
    const d = document.createElement('div');
    d.textContent = String(str);
    return d.innerHTML;
  };

  container.innerHTML = /*html*/`
    <div class="facturas-header">
      <h1>Contactos</h1>
    </div>

    <div class="facturas-filters">
      <div class="search-wrapper">
        <span class="search-icon">${icons.search}</span>
        <input type="search" placeholder="Buscar por nombre, email o teléfono..." class="search-input search-input--with-icon" id="contacts-search" />
      </div>
      <button class="btn-new-invoice" id="btn-new-contact">${icons.plus} <span>Nuevo contacto</span></button>
    </div>

    <div class="invoices-table-container">
      <table class="invoices-table">
        <thead>
          <tr>
            <th>Nombre</th>
            <th>Email</th>
            <th>Teléfono</th>
            <th>Móvil</th>
            <th>Acciones</th>
          </tr>
        </thead>
        <tbody id="contacts-tbody">
          <tr><td colspan="5" class="facturas-empty">Cargando...</td></tr>
        </tbody>
      </table>
    </div>

    <!-- Detail / Edit modal -->
    <div class="modal-overlay sup-detail-overlay" id="contact-detail-overlay" style="display:none">
      <div class="modal-content sup-detail-modal" id="contact-detail-modal">
        <div class="modal-header">
          <h2 id="contact-detail-title">Contacto</h2>
          <button class="btn-close" id="contact-detail-close">×</button>
        </div>
        <div class="modal-body" id="contact-detail-body">
          <div class="loading">Cargando...</div>
        </div>
      </div>
    </div>

    <!-- Create modal -->
    <div class="modal-overlay sup-detail-overlay" id="contact-create-overlay" style="display:none">
      <div class="modal-content sup-detail-modal" id="contact-create-modal">
        <div class="modal-header">
          <h2>Nuevo contacto</h2>
          <button class="btn-close" id="contact-create-close">×</button>
        </div>
        <div class="modal-body">
          <form id="contact-create-form">
            <div class="invoice-detail-grid" style="margin-bottom:1rem">
              <div class="form-field-compact">
                <label>Apellidos *</label>
                <input type="text" id="c-lastname" required style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>Nombre</label>
                <input type="text" id="c-firstname" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact full-width" style="grid-column:1/-1">
                <label>Empresa</label>
                <select id="c-client" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--card-bg);color:var(--text-primary)">
                  <option value="">Sin empresa</option>
                </select>
              </div>
              <div class="form-field-compact">
                <label>Email</label>
                <input type="email" id="c-email" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>Teléfono profesional</label>
                <input type="tel" id="c-phone-pro" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>Teléfono personal</label>
                <input type="tel" id="c-phone-perso" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>Móvil</label>
                <input type="tel" id="c-phone-mobile" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact full-width" style="grid-column:1/-1">
                <label>Dirección</label>
                <input type="text" id="c-address" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>CP</label>
                <input type="text" id="c-zip" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
              <div class="form-field-compact">
                <label>Ciudad</label>
                <input type="text" id="c-town" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
              </div>
            </div>
            <div class="form-actions-compact" style="margin-top:1rem">
              <button type="button" class="btn-cancel-compact" id="contact-create-cancel">Cancelar</button>
              <button type="submit" class="btn-submit-compact" id="contact-create-submit">Crear contacto</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  `;

  const tbody = container.querySelector('#contacts-tbody');
  const searchInput = container.querySelector('#contacts-search');
  const detailOverlay = container.querySelector('#contact-detail-overlay');
  const detailBody = container.querySelector('#contact-detail-body');
  const detailTitle = container.querySelector('#contact-detail-title');
  const createOverlay = container.querySelector('#contact-create-overlay');
  let currentContact = null;

  function applyFilters() {
    const q = searchTerm.toLowerCase();
    filteredContacts = !q ? [...allContacts] : allContacts.filter(c =>
      (c.lastname || '').toLowerCase().includes(q) ||
      (c.firstname || '').toLowerCase().includes(q) ||
      (c.email || '').toLowerCase().includes(q) ||
      (c.phonePro || '').toLowerCase().includes(q) ||
      (c.phoneMobile || '').toLowerCase().includes(q)
    );
    renderTable();
  }

  function renderTable() {
    if (filteredContacts.length === 0) {
      tbody.innerHTML = `<tr><td colspan="5" class="facturas-empty">No hay contactos</td></tr>`;
      return;
    }
    tbody.innerHTML = filteredContacts.map(c => `
      <tr class="invoice-item" data-id="${c.id}">
        <td class="invoice-client">
          <span class="client-icon">${icons.user}</span>
          <button class="btn-invoice-num" data-id="${c.id}">${escHtml([c.lastname, c.firstname].filter(Boolean).join(', ') || '—')}</button>
        </td>
        <td>${escHtml(c.email || '—')}</td>
        <td>${escHtml(c.phonePro || '—')}</td>
        <td>${escHtml(c.phoneMobile || '—')}</td>
        <td class="invoice-actions">
          <button class="btn-action btn-view" data-id="${c.id}" title="Ver detalle">${icons.eye}</button>
          <button class="btn-action" data-delete="${c.id}" title="Eliminar" style="color:var(--danger)">${icons.close}</button>
        </td>
      </tr>
    `).join('');

    tbody.querySelectorAll('[data-id]').forEach(el =>
      el.addEventListener('click', () => openDetail(Number(el.dataset.id)))
    );
    tbody.querySelectorAll('[data-delete]').forEach(el =>
      el.addEventListener('click', (e) => { e.stopPropagation(); confirmDelete(Number(el.dataset.delete)); })
    );
  }

  async function openDetail(id) {
    detailOverlay.style.display = 'flex';
    detailTitle.textContent = 'Cargando...';
    detailBody.innerHTML = '<div class="loading">Cargando...</div>';

    try {
      const c = allContacts.find(x => x.id === id) || await getContactById(id);
      currentContact = c;
      detailTitle.textContent = [c.lastname, c.firstname].filter(Boolean).join(', ') || `Contacto #${c.id}`;
      renderDetailView(c);
    } catch (err) {
      detailBody.innerHTML = `<div class="error">No se pudo cargar: ${escHtml(err.message)}</div>`;
    }
  }

  function renderDetailView(c) {
    detailBody.innerHTML = /*html*/`
      <div id="contact-view-mode">
        <div class="invoice-detail-grid">
          <div class="detail-row"><span class="detail-label">Apellidos</span><span class="detail-value">${escHtml(c.lastname || '—')}</span></div>
          <div class="detail-row"><span class="detail-label">Nombre</span><span class="detail-value">${escHtml(c.firstname || '—')}</span></div>
          <div class="detail-row"><span class="detail-label">Email</span><span class="detail-value">${escHtml(c.email || '—')}</span></div>
          <div class="detail-row"><span class="detail-label">Tel. profesional</span><span class="detail-value">${escHtml(c.phonePro || '—')}</span></div>
          <div class="detail-row"><span class="detail-label">Tel. personal</span><span class="detail-value">${escHtml(c.phonePerso || '—')}</span></div>
          <div class="detail-row"><span class="detail-label">Móvil</span><span class="detail-value">${escHtml(c.phoneMobile || '—')}</span></div>
          ${c.address ? `<div class="detail-row full-width"><span class="detail-label">Dirección</span><span class="detail-value">${escHtml(c.address)}</span></div>` : ''}
          ${(c.zip || c.town) ? `<div class="detail-row"><span class="detail-label">Ciudad</span><span class="detail-value">${escHtml([c.zip, c.town].filter(Boolean).join(' '))}</span></div>` : ''}
        </div>
        <div class="form-actions-compact" style="margin-top:1.5rem">
          <button class="btn-cancel-compact" id="contact-edit-btn">Editar</button>
        </div>
      </div>
    `;
    detailBody.querySelector('#contact-edit-btn').addEventListener('click', () => renderEditView(c));
  }

  function renderEditView(c) {
    detailBody.innerHTML = /*html*/`
      <form id="contact-edit-form">
        <div class="invoice-detail-grid" style="margin-bottom:1rem">
          <div class="form-field-compact">
            <label>Apellidos *</label>
            <input type="text" id="e-lastname" value="${escHtml(c.lastname || '')}" required style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Nombre</label>
            <input type="text" id="e-firstname" value="${escHtml(c.firstname || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Email</label>
            <input type="email" id="e-email" value="${escHtml(c.email || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Tel. profesional</label>
            <input type="tel" id="e-phone-pro" value="${escHtml(c.phonePro || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Tel. personal</label>
            <input type="tel" id="e-phone-perso" value="${escHtml(c.phonePerso || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Móvil</label>
            <input type="tel" id="e-phone-mobile" value="${escHtml(c.phoneMobile || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact full-width" style="grid-column:1/-1">
            <label>Dirección</label>
            <input type="text" id="e-address" value="${escHtml(c.address || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>CP</label>
            <input type="text" id="e-zip" value="${escHtml(c.zip || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
          <div class="form-field-compact">
            <label>Ciudad</label>
            <input type="text" id="e-town" value="${escHtml(c.town || '')}" style="width:100%;padding:0.5rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary)" />
          </div>
        </div>
        <div class="form-actions-compact">
          <button type="button" class="btn-cancel-compact" id="contact-edit-cancel">Cancelar</button>
          <button type="submit" class="btn-submit-compact" id="contact-edit-submit">Guardar</button>
        </div>
      </form>
    `;

    detailBody.querySelector('#contact-edit-cancel').addEventListener('click', () => renderDetailView(c));
    detailBody.querySelector('#contact-edit-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const submitBtn = detailBody.querySelector('#contact-edit-submit');
      submitBtn.disabled = true;
      submitBtn.textContent = 'Guardando...';
      try {
        await updateContact(c.id, {
          lastname: detailBody.querySelector('#e-lastname').value.trim() || undefined,
          firstname: detailBody.querySelector('#e-firstname').value.trim() || undefined,
          email: detailBody.querySelector('#e-email').value.trim() || undefined,
          phonePro: detailBody.querySelector('#e-phone-pro').value.trim() || undefined,
          phonePerso: detailBody.querySelector('#e-phone-perso').value.trim() || undefined,
          phoneMobile: detailBody.querySelector('#e-phone-mobile').value.trim() || undefined,
          address: detailBody.querySelector('#e-address').value.trim() || undefined,
          zip: detailBody.querySelector('#e-zip').value.trim() || undefined,
          town: detailBody.querySelector('#e-town').value.trim() || undefined,
        });
        showToast('Contacto actualizado', 'success');
        await reload();
        const updated = allContacts.find(x => x.id === c.id) || c;
        currentContact = updated;
        detailTitle.textContent = [updated.lastname, updated.firstname].filter(Boolean).join(', ') || `Contacto #${c.id}`;
        renderDetailView(updated);
      } catch (err) {
        showToast(`Error: ${err.message}`, 'error');
        submitBtn.disabled = false;
        submitBtn.textContent = 'Guardar';
      }
    });
  }

  async function confirmDelete(id) {
    const contact = allContacts.find(c => c.id === id);
    const name = contact ? [contact.lastname, contact.firstname].filter(Boolean).join(' ') : `#${id}`;
    if (!confirm(`¿Eliminar el contacto "${name}"? Esta acción no se puede deshacer.`)) return;
    try {
      await deleteContact(id);
      showToast('Contacto eliminado', 'success');
      if (detailOverlay.style.display !== 'none' && currentContact?.id === id) {
        detailOverlay.style.display = 'none';
      }
      await reload();
    } catch (err) {
      showToast(`Error: ${err.message}`, 'error');
    }
  }

  async function reload() {
    try {
      allContacts = await getContacts({ limit: 500 });
    } catch (err) {
      showToast(`Error al actualizar lista: ${err.message}`, 'error');
    }
    applyFilters();
  }

  async function loadClients() {
    if (clients.length > 0) return;
    try {
      clients = await apiGet('/api/Clients?limit=500');
    } catch { clients = []; }
  }

  function populateClientSelect(selectEl) {
    selectEl.innerHTML = '<option value="">Sin empresa</option>';
    clients.forEach(c => {
      const opt = document.createElement('option');
      opt.value = c.id;
      opt.textContent = c.name;
      selectEl.appendChild(opt);
    });
  }

  // Close detail
  container.querySelector('#contact-detail-close').addEventListener('click', () => { detailOverlay.style.display = 'none'; });
  detailOverlay.addEventListener('click', (e) => { if (e.target === detailOverlay) detailOverlay.style.display = 'none'; });

  // Create modal
  container.querySelector('#btn-new-contact').addEventListener('click', async () => {
    await loadClients();
    populateClientSelect(container.querySelector('#c-client'));
    createOverlay.style.display = 'flex';
    container.querySelector('#c-lastname').value = '';
    container.querySelector('#c-firstname').value = '';
    container.querySelector('#c-email').value = '';
    container.querySelector('#c-phone-pro').value = '';
    container.querySelector('#c-phone-perso').value = '';
    container.querySelector('#c-phone-mobile').value = '';
    container.querySelector('#c-address').value = '';
    container.querySelector('#c-zip').value = '';
    container.querySelector('#c-town').value = '';
  });
  container.querySelector('#contact-create-close').addEventListener('click', () => { createOverlay.style.display = 'none'; });
  container.querySelector('#contact-create-cancel').addEventListener('click', () => { createOverlay.style.display = 'none'; });
  createOverlay.addEventListener('click', (e) => { if (e.target === createOverlay) createOverlay.style.display = 'none'; });

  container.querySelector('#contact-create-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const submitBtn = container.querySelector('#contact-create-submit');
    submitBtn.disabled = true;
    submitBtn.textContent = 'Creando...';
    try {
      const clientId = parseInt(container.querySelector('#c-client').value) || 0;
      await createContact({
        lastname: container.querySelector('#c-lastname').value.trim(),
        firstname: container.querySelector('#c-firstname').value.trim() || undefined,
        clientId: clientId > 0 ? clientId : 0,
        email: container.querySelector('#c-email').value.trim() || undefined,
        phonePro: container.querySelector('#c-phone-pro').value.trim() || undefined,
        phonePerso: container.querySelector('#c-phone-perso').value.trim() || undefined,
        phoneMobile: container.querySelector('#c-phone-mobile').value.trim() || undefined,
        address: container.querySelector('#c-address').value.trim() || undefined,
        zip: container.querySelector('#c-zip').value.trim() || undefined,
        town: container.querySelector('#c-town').value.trim() || undefined,
      });
      showToast('Contacto creado', 'success');
      createOverlay.style.display = 'none';
      await reload();
    } catch (err) {
      showToast(`Error: ${err.message}`, 'error');
    } finally {
      submitBtn.disabled = false;
      submitBtn.textContent = 'Crear contacto';
    }
  });

  searchInput.addEventListener('input', () => { searchTerm = searchInput.value; applyFilters(); });

  // Initial load
  (async () => {
    try {
      allContacts = await getContacts({ limit: 500 });
      applyFilters();
    } catch (err) {
      tbody.innerHTML = `<tr><td colspan="5" class="facturas-empty">Error al cargar: ${escHtml(err.message)}</td></tr>`;
      showToast('Error al cargar contactos', 'error');
    }
  })();

  return container;
}
