/* global React */

// ============================================================
// Invoice preview component
// ============================================================

const Invoice = ({ data }) => {
  const { date, number, sender, receiver, items, discount, logo } = data;

  // Parse date into "12 April" + "2026" visually
  const dateParts = (() => {
    if (!date) return { dm: '', y: '' };
    // Expected format input: "18 April 2026" or yyyy-mm-dd
    const isoMatch = date.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (isoMatch) {
      const [_, y, m, d] = isoMatch;
      const months = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
      return { dm: `${parseInt(d, 10)} ${months[parseInt(m,10)-1]}`, y };
    }
    const parts = date.trim().split(/\s+/);
    if (parts.length >= 3) {
      return { dm: `${parts[0]} ${parts[1]}`, y: parts.slice(2).join(' ') };
    }
    return { dm: date, y: '' };
  })();

  const fmt = (n) => {
    if (n === '' || n === null || n === undefined || isNaN(n)) return '';
    return '$' + Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  };

  const computeItemTotal = (it) => {
    const qty = parseFloat(it.qty);
    const price = parseFloat(it.price);
    if (isNaN(qty) || isNaN(price)) return null;
    return qty * price;
  };

  const subtotal = items.reduce((sum, it) => {
    const t = computeItemTotal(it);
    return sum + (t || 0);
  }, 0);

  const discountVal = parseFloat(discount) || 0;
  const total = subtotal - discountVal;

  const phones = [receiver.phone1, receiver.phone2].filter(Boolean).join(' · ');

  return (
    <div className="invoice">
      {/* Left navy panel */}
      <div className="panel-left">
        <div className="date-big">
          <div>{dateParts.dm || <span style={{opacity: .3}}>Fecha</span>}</div>
          <div className="y">{dateParts.y}</div>
        </div>

        <div className="invoice-word">INVOICE</div>
        <div className="invoice-num">{number ? `#${number}` : <span style={{opacity: .4}}>#—</span>}</div>

        <div className="panel-section">
          <h3>ENVÍA</h3>
          <div className="panel-field">
            <div className="panel-label">Nombre y apellido:</div>
            <div className={`panel-value ${!sender.name ? 'empty' : ''}`}>{sender.name}</div>
          </div>
          <div className="panel-field">
            <div className="panel-label">Teléfono:</div>
            <div className={`panel-value ${!sender.phone ? 'empty' : ''}`}>{sender.phone}</div>
          </div>
        </div>

        <div className="panel-section">
          <h3>RECIBE</h3>
          <div className="panel-field">
            <div className="panel-label">Nombre y apellido:</div>
            <div className={`panel-value ${!receiver.name ? 'empty' : ''}`}>{receiver.name}</div>
          </div>
          <div className="panel-field">
            <div className="panel-label">Número de Cédula:</div>
            <div className={`panel-value ${!receiver.id ? 'empty' : ''}`}>{receiver.id}</div>
          </div>
          <div className="panel-field">
            <div className="panel-label">Dos números telefónicos:</div>
            <div className={`panel-value ${!phones ? 'empty' : ''}`}>{phones}</div>
          </div>
          <div className="panel-field">
            <div className="panel-label">Ciudad:</div>
            <div className={`panel-value ${!receiver.city ? 'empty' : ''}`}>{receiver.city}</div>
          </div>
          <div className="panel-field">
            <div className="panel-label">Dirección:</div>
            <div className={`panel-value ${!receiver.address ? 'empty' : ''}`} style={{whiteSpace: 'pre-line'}}>{receiver.address}</div>
          </div>
        </div>
      </div>

      {/* Right panel */}
      <div className="panel-right">
        <div className="brand-row">
          <div className="brand">
            {logo ? (
              <img src={logo} alt="OLA EXPRESS" />
            ) : (
              <span className="brand-wordmark">
                OLA<span className="accent"> </span>EXPRESS
              </span>
            )}
          </div>
        </div>

        <div className="company-info">
          <div className="name">OLA EXPRESS</div>
          <div>469.919.7541</div>
          <div>406 Business Pkwy, Richardson, TX 75081</div>
        </div>

        <table className="items-table">
          <thead>
            <tr>
              <th>ITEM</th>
              <th className="num">CANT.</th>
              <th className="num">MODO</th>
              <th className="num">PRECIO</th>
              <th className="num">TOTAL</th>
            </tr>
          </thead>
          <tbody>
            {items.length === 0 ? (
              <tr className="empty-row">
                <td colSpan={5} style={{padding: '18px 0', textAlign: 'center'}}>— Sin items —</td>
              </tr>
            ) : items.map((it, i) => {
              const t = computeItemTotal(it);
              const mode = it.mode || 'air';
              return (
                <tr key={i}>
                  <td className="desc">{it.desc || <span style={{color: '#bbb'}}>Descripción</span>}</td>
                  <td className="num">{it.qty || ''}</td>
                  <td className="num">
                    <span className={`mode-pill mode-${mode}`}>
                      {mode === 'mar' ? 'MAR' : 'AIR'}
                    </span>
                  </td>
                  <td className="num">{fmt(it.price)}</td>
                  <td className="num">{t !== null ? fmt(t) : ''}</td>
                </tr>
              );
            })}
          </tbody>
        </table>

        <div className="totals">
          <div className="totals-row">
            <span className="label">Subtotal</span>
            <span className="value">{fmt(subtotal)}</span>
          </div>
          <div className="totals-row">
            <span className="label">Descuento</span>
            <span className="value">{fmt(discountVal)}</span>
          </div>
          <div className="totals-row total">
            <span className="label">Total</span>
            <span className="value">{fmt(total)}</span>
          </div>
        </div>

        <div className="signature">
          <div className="sig-icon">
            {/* Simple pencil glyph */}
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 20h9" />
              <path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
            </svg>
          </div>
          <div>
            <div className="sig-line">&nbsp;</div>
            <div className="sig-label">Firma del cliente</div>
          </div>
        </div>

        <div className="delivery-box">
          <div className="title">TIEMPO ESTIMADO DE ENTREGA</div>
          <div><strong>Marítimo:</strong> 5 a 7 semanas desde su salida.</div>
          <div><strong>Aéreo:</strong> 4 a 9 días hábiles desde su salida.</div>
        </div>
      </div>

      {/* Bottom ocre strip — payment method */}
      <div className="panel-bottom">
        <div className="method-title">MÉTODO DE PAGO:</div>
        <div className="method-grid">
          <div>
            <div className="method-label">Titular de cuenta</div>
            <div className="method-value">{data.paymentHolder || 'Ola Express LLC'}</div>
          </div>
          <div>
            <div className="method-label">{data.paymentMethod || 'Zelle'}</div>
            <div className="method-value">{data.paymentDetail || ''}</div>
          </div>
          <div className="due-block">
            <div className="method-label">Due date</div>
            <div className="method-value">{data.dueDate || '\u00A0'}</div>
          </div>
        </div>

        {/* Decorative wave — simple abstract curl, not company logo */}
        <svg className="wave" viewBox="0 0 260 200" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M 260 200 Q 260 120 200 120 Q 130 120 130 60 Q 130 20 170 20 Q 210 20 210 60 Q 210 90 190 90 Q 170 90 170 70"
            fill="none"
            stroke="#1B365D"
            strokeWidth="22"
            strokeLinecap="round"
          />
        </svg>
      </div>
    </div>
  );
};

window.Invoice = Invoice;
