import { icons } from '../services/icons.js';

export function InvoiceItem(invoice, onView) {
  const item = document.createElement('tr');
  item.className = 'invoice-item';

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES');
  };

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

  const getStatusClass = (status) => {
    const statusMap = {
      'draft':     'status-draft',
      'validated': 'status-validated',
      'paid':      'status-paid',
      'unpaid':    'status-unpaid',
      'canceled':  'status-canceled',
      'pending':   'status-pending',
    };
    return statusMap[status] || 'status-draft';
  };

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

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

  item.innerHTML = /*html*/`
    <td class="invoice-select-col">
      <input type="checkbox" class="invoice-check" value="${invoice.id}" aria-label="Seleccionar factura ${escapeHtml(invoice.number)}" />
    </td>
    <td class="invoice-number">
      <button class="btn-invoice-num" title="Ver detalles">${escapeHtml(invoice.number)}</button>
    </td>
    <td class="invoice-status">
      <span class="status-badge ${getStatusClass(invoice.status)}">
        ${escapeHtml(getStatusText(invoice.status))}
      </span>
    </td>
    <td class="invoice-client">
      <span class="client-icon">${icons.user}</span>
      ${escapeHtml(invoice.clientName || 'Sin nombre')}
    </td>
    <td class="invoice-date">${formatDate(invoice.date)}</td>
    <td class="invoice-total amount-positive">${formatCurrency(invoice.total)}</td>
    <td class="invoice-remain ${invoice.status === 'paid' ? 'amount-muted' : 'amount-pending'}">${invoice.status === 'paid' ? '—' : formatCurrency(invoice.remainToPay)}</td>
    <td class="invoice-actions">
      <button class="btn-action btn-view" data-invoice-id="${invoice.id}" title="Ver/Editar detalles">
        ${icons.eye}
      </button>
    </td>
  `;

  item.querySelector('.btn-invoice-num').addEventListener('click', () => onView?.(invoice.id));

  const viewBtn = item.querySelector('.btn-view');
  viewBtn.addEventListener('click', () => onView?.(invoice.id));

  return item;
}