import { ClientItem } from '../components/ClientItem.js';
import { createClient, getClients } from '../services/clients.js';
import { icons } from '../services/icons.js';
import { toast } from '../services/toast.js';

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

  let currentPage = 1;
  let totalPages = 1;
  const pageSize = 20;
  let allClients = [];
  let filteredClients = [];
  let searchTerm = '';

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

    <div class="clientes-filters">
      <div class="search-wrapper">
        <span class="search-icon">${icons.search}</span>
        <input type="search" placeholder="Buscar terceros..." class="search-input search-input--with-icon" />
      </div>
      <button class="btn-new-client">
        ${icons.plus} Nuevo tercero
      </button>
    </div>

    <div class="clients-table-container">
      <table class="clients-table">
        <thead>
          <tr>
            <th class="client-avatar-col"></th>
            <th class="client-name-col">Nombre / Código</th>
            <th class="client-type-col">Tipo</th>
            <th class="client-status-col">Estado</th>
            <th class="client-email-col">Email</th>
            <th class="client-phone-col">Teléfono</th>
            <th class="client-actions-col">Acciones</th>
          </tr>
        </thead>
        <tbody class="clients-list">
          <tr><td colspan="7" class="loading">Cargando terceros...</td></tr>
        </tbody>
      </table>
    </div>

    <div class="pagination">
      <button class="btn-pagination btn-prev">← Anterior</button>
      <div class="pagination-info">
        <span class="current-page">1</span> / <span class="total-pages">1</span>
      </div>
      <button class="btn-pagination btn-next">Siguiente →</button>
    </div>
  `;

  function displayValue(value) {
    if (value === null || value === undefined || value === '' || value === 'null') return 'N/A';
    return value;
  }

  function escapeHtml(str) {
    if (str == null) return '';
    const div = document.createElement('div');
    div.textContent = String(str);
    return div.innerHTML;
  }

  function getClientStatusText(status) {
    const statusMap = { '0': 'Inactivo', '1': 'Activo' };
    return statusMap[status] || 'N/A';
  }

  function applyFilters() {
    if (!searchTerm) {
      filteredClients = [...allClients];
    } else {
      const term = searchTerm.toLowerCase();
      filteredClients = allClients.filter(client => {
        const nameMatch = client.name?.toLowerCase().includes(term);
        const codeMatch = client.codeClient?.toLowerCase().includes(term);
        const emailMatch = client.email?.toLowerCase().includes(term);
        const phoneMatch = client.phone?.toLowerCase().includes(term);
        const contactMatch = client.contacts?.some(c =>
          c.firstname?.toLowerCase().includes(term) ||
          c.lastname?.toLowerCase().includes(term) ||
          c.email?.toLowerCase().includes(term)
        );
        return nameMatch || codeMatch || emailMatch || phoneMatch || contactMatch;
      });
    }
    renderPage(1);
  }

  function renderPage(page = 1) {
    const clientsList = container.querySelector('.clients-list');

    currentPage = page;
    totalPages = Math.ceil(filteredClients.length / pageSize);

    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, filteredClients.length);
    const clients = filteredClients.slice(startIndex, endIndex);

    updatePaginationUI();

    clientsList.innerHTML = '';

    if (clients.length === 0) {
      clientsList.innerHTML = `<tr><td colspan="7"><div class="empty-state">${icons.emptyClients}<h3>No hay terceros</h3><p>Los terceros aparecerán aquí una vez añadidos.</p></div></td></tr>`;
      return;
    }

    clients.forEach(client => {
      const clientItem = ClientItem(client, handleViewClient);
      clientsList.appendChild(clientItem);
    });
  }

  function handleViewClient(clientId) {
    const client = allClients.find(c => c.id === clientId);
    if (client) {
      showClientModal(client);
    }
  }

  function showClientModal(client) {
    const modal = document.createElement('div');
    modal.className = 'client-modal-overlay';

    const contactsHtml = client.contacts && client.contacts.length > 0
      ? client.contacts.map(contact => `
          <div class="contact-card">
            <div class="contact-header">
              <div class="contact-avatar">${icons.user}</div>
              <span class="contact-full-name">${escapeHtml(displayValue(contact.firstname))} ${escapeHtml(displayValue(contact.lastname))}</span>
            </div>
            <div class="contact-details">
              ${contact.email ? `<div class="contact-row"><span class="contact-icon">${icons.mail}</span><span>${escapeHtml(displayValue(contact.email))}</span></div>` : ''}
              ${contact.phoneMobile ? `<div class="contact-row"><span class="contact-icon">${icons.mobile}</span><span>${escapeHtml(displayValue(contact.phoneMobile))}</span></div>` : ''}
              ${contact.phonePro ? `<div class="contact-row"><span class="contact-icon">${icons.phone}</span><span>${escapeHtml(displayValue(contact.phonePro))}</span></div>` : ''}
              ${contact.phonePerso ? `<div class="contact-row"><span class="contact-icon">${icons.phone}</span><span>${escapeHtml(displayValue(contact.phonePerso))}</span></div>` : ''}
            </div>
          </div>
        `).join('')
      : '<p class="no-contacts">No hay contactos registrados</p>';

    modal.innerHTML = /*html*/`
      <div class="client-modal">
        <div class="client-modal-header">
          <h2>${escapeHtml(displayValue(client.name))}</h2>
          <button class="btn-close-modal">${icons.close}</button>
        </div>
        <div class="client-modal-body">
          <div class="client-info-section">
            <h3>Información del Tercero</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">ID</span>
                <span class="info-value">${escapeHtml(client.id)}</span>
              </div>
              <div class="info-item">
                <span class="info-label">Código</span>
                <span class="info-value">${escapeHtml(displayValue(client.codeClient))}</span>
              </div>
              <div class="info-item">
                <span class="info-label">Tipo</span>
                <span class="info-value">${{ client: 'Cliente', supplier: 'Proveedor', both: 'Ambos' }[client.role] || 'N/A'}</span>
              </div>
              <div class="info-item">
                <span class="info-label">Estado</span>
                <span class="info-value">${escapeHtml(getClientStatusText(client.status))}</span>
              </div>
              <div class="info-item">
                <span class="info-label">Email</span>
                <span class="info-value">${escapeHtml(displayValue(client.email))}</span>
              </div>
              <div class="info-item">
                <span class="info-label">Teléfono</span>
                <span class="info-value">${escapeHtml(displayValue(client.phone))}</span>
              </div>
            </div>
          </div>
          <div class="contacts-section">
            <h3>Contactos (${client.contacts?.length || 0})</h3>
            <div class="contacts-list">
              ${contactsHtml}
            </div>
          </div>
        </div>
      </div>
    `;

    const closeBtn = modal.querySelector('.btn-close-modal');
    closeBtn.addEventListener('click', () => modal.remove());
    modal.addEventListener('click', (e) => {
      if (e.target === modal) modal.remove();
    });

    document.body.appendChild(modal);
  }

  function showCreateClientModal() {
    const overlay = document.createElement('div');
    overlay.className = 'client-modal-overlay';
    overlay.innerHTML = /*html*/`
      <div class="client-modal create-client-modal">
        <div class="client-modal-header">
          <h2>Nuevo tercero</h2>
          <button class="btn-close-modal" type="button">${icons.close}</button>
        </div>
        <form class="create-client-form" novalidate>
          <div class="client-modal-body">
            <div class="create-client-section">
              <h3>Información básica</h3>
              <div class="create-client-grid">
                <div class="form-field form-field--full">
                  <label class="form-label" for="cc-name">Nombre <span class="form-required">*</span></label>
                  <input id="cc-name" name="name" type="text" class="form-input" placeholder="Nombre o razón social" required maxlength="200" />
                  <span class="form-error" id="cc-name-error"></span>
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-role">Tipo <span class="form-required">*</span></label>
                  <select id="cc-role" name="role" class="form-input">
                    <option value="client">Cliente</option>
                    <option value="supplier">Proveedor</option>
                    <option value="both">Ambos</option>
                  </select>
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-email">Email</label>
                  <input id="cc-email" name="email" type="email" class="form-input" placeholder="empresa@ejemplo.com" maxlength="200" />
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-phone">Teléfono</label>
                  <input id="cc-phone" name="phone" type="tel" class="form-input" placeholder="+34 600 000 000" maxlength="20" />
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-vat">NIF / CIF / VAT</label>
                  <input id="cc-vat" name="vatNumber" type="text" class="form-input" placeholder="B12345678" maxlength="50" />
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-country">País (código)</label>
                  <input id="cc-country" name="countryCode" type="text" class="form-input" placeholder="ES" maxlength="50" />
                </div>
              </div>
            </div>

            <div class="create-client-section">
              <h3>Dirección</h3>
              <div class="create-client-grid">
                <div class="form-field form-field--full">
                  <label class="form-label" for="cc-address">Dirección</label>
                  <input id="cc-address" name="address" type="text" class="form-input" placeholder="Calle, número, piso..." maxlength="50" />
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-zip">Código postal</label>
                  <input id="cc-zip" name="zip" type="text" class="form-input" placeholder="46001" maxlength="50" />
                </div>
                <div class="form-field">
                  <label class="form-label" for="cc-town">Ciudad</label>
                  <input id="cc-town" name="town" type="text" class="form-input" placeholder="Valencia" maxlength="50" />
                </div>
              </div>
            </div>

            <div class="create-client-section">
              <h3>Notas</h3>
              <div class="create-client-grid">
                <div class="form-field form-field--full">
                  <label class="form-label" for="cc-note-pub">Nota pública</label>
                  <textarea id="cc-note-pub" name="notePublic" class="form-input form-textarea" placeholder="Visible para el cliente..." maxlength="500" rows="2"></textarea>
                </div>
                <div class="form-field form-field--full">
                  <label class="form-label" for="cc-note-priv">Nota privada</label>
                  <textarea id="cc-note-priv" name="notePrivate" class="form-input form-textarea" placeholder="Solo visible internamente..." maxlength="500" rows="2"></textarea>
                </div>
              </div>
            </div>
          </div>

          <div class="create-client-footer">
            <button type="button" class="btn-cancel-create">Cancelar</button>
            <button type="submit" class="btn-submit-create">
              <span class="btn-submit-text">Crear cliente</span>
              <span class="btn-submit-spinner" hidden>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="animation:spin .7s linear infinite;display:block"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
              </span>
            </button>
          </div>
        </form>
      </div>
    `;

    const form = overlay.querySelector('.create-client-form');
    const nameInput = overlay.querySelector('#cc-name');
    const nameError = overlay.querySelector('#cc-name-error');
    const submitBtn = overlay.querySelector('.btn-submit-create');
    const submitText = overlay.querySelector('.btn-submit-text');
    const submitSpinner = overlay.querySelector('.btn-submit-spinner');

    const close = () => overlay.remove();
    overlay.querySelector('.btn-close-modal').addEventListener('click', close);
    overlay.querySelector('.btn-cancel-create').addEventListener('click', close);
    overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });

    const handleEscape = (e) => {
      if (e.key !== 'Escape') return;
      if (!overlay.isConnected) { document.removeEventListener('keydown', handleEscape); return; }
      close();
    };
    document.addEventListener('keydown', handleEscape);

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      nameError.textContent = '';

      const name = nameInput.value.trim();
      if (!name) {
        nameError.textContent = 'El nombre es obligatorio.';
        nameInput.focus();
        return;
      }

      const getData = (n) => {
        const v = form.elements[n]?.value?.trim();
        return v || undefined;
      };

      const payload = {
        Name: name,
        Role: getData('role') || 'client',
        Email: getData('email'),
        Phone: getData('phone'),
        VatNumber: getData('vatNumber'),
        CountryCode: getData('countryCode'),
        Address: getData('address'),
        Zip: getData('zip'),
        Town: getData('town'),
        NotePublic: getData('notePublic'),
        NotePrivate: getData('notePrivate'),
      };

      submitBtn.disabled = true;
      submitText.hidden = true;
      submitSpinner.hidden = false;

      try {
        await createClient(payload);
        toast.success(`Tercero "${name}" creado correctamente.`);
        close();
        await loadAllClients();
      } catch (err) {
        toast.error(err.message || 'Error al crear el cliente.');
        submitBtn.disabled = false;
        submitText.hidden = false;
        submitSpinner.hidden = true;
      }
    });

    document.body.appendChild(overlay);
    setTimeout(() => nameInput.focus(), 50);
  }

  async function loadAllClients() {
    const clientsList = container.querySelector('.clients-list');

    try {
      clientsList.innerHTML = '<tr><td colspan="7" class="loading">Cargando terceros...</td></tr>';

      const data = await getClients(1000, 1);

      allClients = Array.isArray(data) ? data : data.data || data.clients || [];
      filteredClients = [...allClients];

      renderPage(1);
    } catch (error) {
      console.error('Error al cargar clientes:', error);
      clientsList.innerHTML = `<tr><td colspan="7"><div class="empty-state">${icons.error}<h3>Error al cargar</h3><p>No se pudieron cargar los terceros. Inténtalo de nuevo.</p></div></td></tr>`;
    }
  }

  function updatePaginationUI() {
    const paginationDiv = container.querySelector('.pagination');
    const currentPageSpan = container.querySelector('.current-page');
    const totalPagesSpan = container.querySelector('.total-pages');
    const btnPrev = container.querySelector('.btn-prev');
    const btnNext = container.querySelector('.btn-next');

    currentPageSpan.textContent = currentPage;
    totalPagesSpan.textContent = totalPages;

    if (totalPages <= 1) {
      paginationDiv.style.display = 'none';
    } else {
      paginationDiv.style.display = 'flex';
    }

    btnPrev.disabled = currentPage === 1;
    btnNext.disabled = currentPage === totalPages;
  }

  container.querySelector('.btn-new-client').addEventListener('click', showCreateClientModal);

  const searchInput = container.querySelector('.search-input');
  searchInput.addEventListener('input', (e) => {
    clearTimeout(searchInput._debounceTimer);
    searchInput._debounceTimer = setTimeout(() => {
      searchTerm = e.target.value.trim();
      applyFilters();
    }, 300);
  });

  container.querySelector('.btn-prev').addEventListener('click', () => {
    if (currentPage > 1) { renderPage(currentPage - 1); scrollToTop(); }
  });

  container.querySelector('.btn-next').addEventListener('click', () => {
    if (currentPage < totalPages) { renderPage(currentPage + 1); scrollToTop(); }
  });

  function scrollToTop() {
    container.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  loadAllClients();

  return container;
}