// js/components/widgets/notas_frete/NotaFreteFormModal.jsx
// [Wave NotasFrete 2026-05-19 v223.23] Extraído de pages/NotasFrete.jsx L473-616 (modal NEW/EDIT).
// Props (5 objetos agregados): mode, form, items, config, actions, helpers.
// Padrão: IIFE + window.ZNX.widgets.notas_frete.NotaFreteFormModal.
(function() {
  'use strict';

  function NotaFreteFormModal({ form, itemForm, config, actions, helpers }) {
    const { state: f, setState: setForm, items: formItems, saving } = form;
    const { state: itf, setState: setItemForm } = itemForm;
    const { carriers, products, productMap, modalMode, formTotalUSD, formTotalBRL } = config;
    const { onClose, onSave, onAddItem, onRemoveItem } = actions;
    const { fmtUSD, fmtBRL, Th, Field } = helpers;

    return (
      <Modal title={modalMode === 'new' ? 'Nova Nota de Frete' : 'Editar Nota'} onClose={onClose} large>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* Cabeçalho da nota */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Freteiro*">
              <select value={f.carrier_id} onChange={e => setForm(p => ({ ...p, carrier_id: e.target.value }))}
                      disabled={modalMode === 'edit'}
                      style={modalMode === 'edit' ? { background: '#F3F4F6' } : {}}>
                <option value="">Selecione...</option>
                {carriers.filter(c => c.active || c.id === f.carrier_id).map(c =>
                  <option key={c.id} value={c.id}>{c.name}</option>
                )}
              </select>
              {modalMode === 'edit' && <span style={{ fontSize: 11, color: '#9CA3AF', marginTop: 2 }}>Freteiro não pode mudar após criada</span>}
            </Field>
            <Field label="Modelo do Frete">
              <input type="text" value={f.freight_model} onChange={e => setForm(p => ({ ...p, freight_model: e.target.value }))}
                     placeholder="Ex: Caminhonete Hilux" />
            </Field>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            <Field label="Custo Frete USD">
              <input type="number" min="0" step="0.01" value={f.total_cost_usd}
                     onChange={e => setForm(p => ({ ...p, total_cost_usd: e.target.value }))} />
            </Field>
            <Field label="Câmbio USD/BRL*">
              <div style={{ display: 'flex', gap: 4 }}>
                <input type="number" min="0.01" step="0.0001" value={f.exchange_rate_usd_brl}
                       onChange={e => setForm(p => ({ ...p, exchange_rate_usd_brl: e.target.value }))}
                       style={{ flex: 1 }} />
                <button type="button" className="btn-outline btn-sm" disabled
                        title="Integração BCB virá em onda futura"
                        style={{ padding: '4px 8px', fontSize: 11, opacity: 0.6 }}>
                  ↻ BCB
                </button>
              </div>
              <span style={{ fontSize: 11, color: '#9CA3AF', marginTop: 2 }}>Travado na emissão da nota</span>
            </Field>
            <Field label="Fonte do câmbio">
              <select value={f.exchange_rate_source} onChange={e => setForm(p => ({ ...p, exchange_rate_source: e.target.value }))}>
                <option value="manual">Manual</option>
                <option value="bcb">BCB</option>
                <option value="wise">Wise</option>
              </select>
            </Field>
          </div>

          <Field label="Notas (opcional)">
            <textarea value={f.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))}
                      rows={2} placeholder="Observações da nota" style={{ width: '100%', resize: 'vertical' }} />
          </Field>

          {/* ITEMS */}
          <div style={{ marginTop: 8, paddingTop: 12, borderTop: '1px solid #E4E7EC' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#374151', marginBottom: 10 }}>
              Items da nota ({formItems.length})
            </div>

            {/* Add item */}
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: 8, marginBottom: 12, alignItems: 'end' }}>
              <Field label="Produto">
                <select value={itf.product_id} onChange={e => setItemForm(p => ({ ...p, product_id: e.target.value }))}>
                  <option value="">Selecione...</option>
                  {products.filter(p => !formItems.some(i => i.product_id === p.id)).map(p =>
                    <option key={p.id} value={p.id}>{p.name}{p.volume ? ' · ' + p.volume : ''}</option>
                  )}
                </select>
              </Field>
              <Field label="Qty esperada">
                <input type="number" min="1" step="1" value={itf.expected_qty}
                       onChange={e => setItemForm(p => ({ ...p, expected_qty: e.target.value }))} />
              </Field>
              <Field label="Custo unit. USD">
                <input type="number" min="0" step="0.01" value={itf.unit_cost_usd}
                       onChange={e => setItemForm(p => ({ ...p, unit_cost_usd: e.target.value }))} />
              </Field>
              <button type="button" className="btn-gold btn-sm" onClick={onAddItem}
                      style={{ padding: '8px 14px', whiteSpace: 'nowrap' }}>
                + Adicionar
              </button>
            </div>

            {/* Lista items adicionados */}
            {formItems.length > 0 && (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginBottom: 12 }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    <Th>Produto</Th>
                    <Th right>Qty</Th>
                    <Th right>USD/un.</Th>
                    <Th right>Sub-total USD</Th>
                    <Th></Th>
                  </tr>
                </thead>
                <tbody>
                  {formItems.map((it, idx) => {
                    const p = productMap[it.product_id];
                    const subUSD = Number(it.expected_qty) * Number(it.unit_cost_usd);
                    return (
                      <tr key={idx} style={{ borderBottom: '1px solid #F3F4F6' }}>
                        <td style={{ padding: '8px 10px', fontWeight: 500 }}>
                          {p?.name || it.product_id}
                          {p?.volume && <span style={{ color: '#9CA3AF' }}> · {p.volume}</span>}
                        </td>
                        <td style={{ padding: '8px 10px', textAlign: 'right' }}>{it.expected_qty}</td>
                        <td style={{ padding: '8px 10px', textAlign: 'right' }}>{fmtUSD(it.unit_cost_usd)}</td>
                        <td style={{ padding: '8px 10px', textAlign: 'right', fontWeight: 600 }}>{fmtUSD(subUSD)}</td>
                        <td style={{ padding: '8px 10px', textAlign: 'right' }}>
                          <button type="button" className="btn-danger btn-sm"
                                  onClick={() => onRemoveItem(idx)}
                                  style={{ padding: '2px 8px', fontSize: 11 }}>
                            ×
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}

            {/* Resumo total */}
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 14px', background: '#F0F9FF', border: '1px solid #BAE6FD', borderRadius: 8 }}>
              <div style={{ fontSize: 12, color: '#0369A1' }}>
                <strong>{formItems.length}</strong> items · Total mercadoria: <strong>{fmtUSD(formTotalUSD)}</strong>
              </div>
              <div style={{ fontSize: 12, color: '#0369A1' }}>
                Equivalente em BRL: <strong>{fmtBRL(formTotalBRL)}</strong>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
            <button className="btn-outline" onClick={onClose} disabled={saving}>Cancelar</button>
            <button className="btn-gold" onClick={onSave} disabled={saving}>
              {saving ? '⏳ Salvando...' : (modalMode === 'new' ? '✓ Criar Nota' : '✓ Salvar')}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.notas_frete = window.ZNX.widgets.notas_frete || {};
  window.ZNX.widgets.notas_frete.NotaFreteFormModal = NotaFreteFormModal;
})();
