// js/components/widgets/entradas/NotaFormModal.jsx
// [Wave 23 v224.4 NUCLEAR] Modal "Nova Nota do Freteiro"
// Extraído de pages/Entradas.jsx L1221-1286 (literal)
//
// Deps runtime globals: Modal, SmartSelect, nid, toast
(function(){
  'use strict';

  function NotaFormModal(props){
    const Modal = window.Modal;
    const SmartSelect = window.SmartSelect;
    if(!Modal){
      const _msg = '[NotaFormModal] Modal global faltando';
      console.error(_msg);
      if(window.Sentry && typeof window.Sentry.captureMessage === 'function'){
        window.Sentry.captureMessage(_msg, 'error');
      }
      return null;
    }

    const {notaForm, setNotaForm, notaItemForm, setNotaItemForm,
      suppliers, products, warehouses,
      onSave, onCancel, isSavingNota} = props;

    function addNotaItem(){
      if(!notaItemForm.productId || notaItemForm.qtdEsperada<1) return;
      const dup = (notaForm.items||[]).find(function(i){
        return typeof nid==='function' ? nid(i.productId, notaItemForm.productId) : String(i.productId)===String(notaItemForm.productId);
      });
      if(dup){
        if(typeof toast==='function') toast('Produto já adicionado nesta nota');
        return;
      }
      setNotaForm(function(f){
        var n = Object.assign({}, f);
        n.items = (f.items||[]).concat([{productId:notaItemForm.productId, qtdEsperada:Number(notaItemForm.qtdEsperada)}]);
        return n;
      });
      setNotaItemForm({productId:'', qtdEsperada:1});
    }

    return (
      <Modal title="🚚 Nova Nota do Freteiro" onClose={onCancel} large>
        <div className="form-grid" style={{marginBottom:14}}>
          <div className="form-group"><label>Número da Nota</label><input value={notaForm.number} onChange={function(e){setNotaForm(function(f){var n=Object.assign({},f); n.number=e.target.value; return n;});}}/></div>
          <div className="form-group"><label>Freteiro</label><input value={notaForm.freteiro} onChange={function(e){setNotaForm(function(f){var n=Object.assign({},f); n.freteiro=e.target.value; return n;});}} placeholder="Ex: DHL, FedEx, Rápido Cargo..."/></div>
          <div className="form-group">
            <label>Fornecedor (opcional)</label>
            {SmartSelect && (
              <SmartSelect value={notaForm.supplierId||''} onChange={function(val){setNotaForm(function(f){var n=Object.assign({},f); n.supplierId = val?Number(val):''; return n;});}}
                placeholder="— Selecione —"
                options={[{value:'',label:'— Selecione —'}].concat((suppliers||[]).map(function(s){return {value:s.id, label:s.name};}))}/>
            )}
          </div>
          <div className="form-group"><label>Data</label><input type="date" value={notaForm.date} onChange={function(e){setNotaForm(function(f){var n=Object.assign({},f); n.date=e.target.value; return n;});}}/></div>
          {warehouses.length>1 && (
            <div className="form-group">
              <label>Depósito de destino <span style={{color:'#DC2626'}}>*</span></label>
              <select value={notaForm.warehouseId||''} onChange={function(e){setNotaForm(function(f){var n=Object.assign({},f); n.warehouseId=e.target.value; return n;});}}
                style={{width:'100%',padding:'8px 10px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13,background:'#fff',fontWeight:600}}>
                {warehouses.map(function(w){return <option key={w.id} value={w.id}>{w.name}{w.is_principal?' (principal)':''}</option>;})}
              </select>
              <div style={{fontSize:11,color:'#6B7280',marginTop:3}}>
                Todos os itens desta nota irão pra este depósito ao serem recebidos.
              </div>
            </div>
          )}
          <div className="form-group full"><label>Observações</label><input value={notaForm.notes} onChange={function(e){setNotaForm(function(f){var n=Object.assign({},f); n.notes=e.target.value; return n;});}} placeholder="Ex: Entrega prevista em 3 viagens, remessa aérea..."/></div>
        </div>

        <div style={{fontWeight:700,fontSize:13,color:'#1C1C28',marginBottom:10}}>Produtos Esperados</div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 140px auto',gap:8,alignItems:'end',marginBottom:10}}>
          <div className="form-group" style={{margin:0}}>
            <label>Produto</label>
            {SmartSelect && (
              <SmartSelect value={notaItemForm.productId||''} onChange={function(val){setNotaItemForm(function(f){var n=Object.assign({},f); n.productId=val; return n;});}}
                placeholder="Selecionar produto..."
                options={[{value:'',label:'Selecionar produto...'}].concat((products||[]).filter(function(p){return !(notaForm.items||[]).find(function(i){return typeof nid==='function' ? nid(i.productId,p.id) : String(i.productId)===String(p.id);});}).map(function(p){return {value:p.id, label:p.name};}))}/>
            )}
          </div>
          <div className="form-group" style={{margin:0}}><label>Qtd Esperada</label><input type="number" min="1" value={notaItemForm.qtdEsperada} onChange={function(e){setNotaItemForm(function(f){var n=Object.assign({},f); n.qtdEsperada=e.target.value; return n;});}}/></div>
          <button className="btn-gold" onClick={addNotaItem} disabled={!notaItemForm.productId} style={{marginBottom:0}}>+ Add</button>
        </div>

        {(notaForm.items||[]).length>0 && (
          <div style={{background:'#F9FAFB',border:'1px solid #F3F4F6',borderRadius:8,overflow:'hidden',marginBottom:14}}>
            <table>
              <thead><tr><th>Produto</th><th>Qtd Esperada</th><th></th></tr></thead>
              <tbody>
                {notaForm.items.map(function(item,i){
                  const p = (products||[]).find(function(x){return typeof nid==='function' ? nid(x.id, item.productId) : String(x.id)===String(item.productId);});
                  return (
                    <tr key={i}>
                      <td style={{fontWeight:500}}>{(p && p.name)||'—'}</td>
                      <td><strong>{item.qtdEsperada} un.</strong></td>
                      <td>
                        <button className="btn-danger btn-sm" onClick={function(){setNotaForm(function(f){var n=Object.assign({},f); n.items=(f.items||[]).filter(function(_,j){return j!==i;}); return n;});}}>✕</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        <div style={{display:'flex',gap:10,justifyContent:'flex-end'}}>
          <button className="btn-outline" onClick={onCancel} disabled={isSavingNota}>Cancelar</button>
          <button className="btn-gold" onClick={onSave} disabled={!notaForm.freteiro||(notaForm.items||[]).length===0||isSavingNota}
            style={{opacity:isSavingNota?0.6:1,cursor:isSavingNota?'not-allowed':'pointer'}}>{isSavingNota?'⏳ Salvando…':'Salvar Nota'}</button>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.entradas = window.ZNX.widgets.entradas || {};
  window.ZNX.widgets.entradas.NotaFormModal = NotaFormModal;
})();
