// js/components/widgets/depositos/TransferDetailModal.jsx
// [Wave 3 KIMI 2026-05-15] Extraído de Depositos.jsx — refactor mecânico zero-lógica.
// Self-contained: zero closures escopo pai.
// Globals runtime: window.sb (Supabase), toast, Modal, window.crypto, React.Fragment.
//
// Props (preservadas byte-by-byte):
//   user, transfer, warehouses, products, onClose, onAction
(function() {
  'use strict';
  const {useState} = React;

  function TransferDetailModal({user, transfer: t, warehouses, products, allUsers, onClose, onAction}){
    const sb = window.sb;
    const [busy, setBusy] = useState(false);
    // [v224.41 G 20260526] Helpers timeline · nome+hora embaixo de cada step alcançado
    const uname = function(id){
      if(!id) return '—';
      var u = (allUsers||[]).find(function(x){return x.id === id;});
      return u ? (u.name || u.username || '—') : '—';
    };
    const fmtHM = function(iso){
      if(!iso) return '';
      var d = new Date(iso);
      return d.toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'}) + ' ' + d.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
    };
    // [v224.46] usar quantity_sent mesmo quando 0 (peça vendida · clamp backend enviou 0).
    // Antes 't.quantity_sent || requested' tratava 0 como falsy → caía pro requested → travava recebimento.
    const [qtyReceived, setQtyReceived] = useState(t.quantity_sent != null ? t.quantity_sent : t.quantity_requested);
    const [divReason, setDivReason] = useState('');
    const [divAction, setDivAction] = useState('PERDA');
    const [divNotes, setDivNotes] = useState('');
    const [cancelReason, setCancelReason] = useState('');

    // [v224.30 2026-05-26] Estoquista (Ibra/Abbes/Munir) liberado workflow transferência completo.
    // Backend: transfer_approve/cancel/resolve_divergence agora permitem · receive/send já permitiam.
    const canManage = window.canManageTransfer?.(user) ?? false;
    const isMyFromWh = warehouses.find(w=>w.id===t.from_warehouse_id)?.manager_app_user_id === user.id;
    const isMyToWh = warehouses.find(w=>w.id===t.to_warehouse_id)?.manager_app_user_id === user.id;
    const wname = (id)=>warehouses.find(w=>w.id===id)?.name||'?';
    const pname = (id)=>{ const p=(products||[]).find(p=>p.id===id); return p?`${p.brand||''} ${p.name||''}`.trim():'?'; };

    // [DEP100-O1-D] callRpc agora gera idem_key UUID por click
    const callRpc = async (fn, params)=>{
      setBusy(true);
      try{
        const idem = (window.crypto?.randomUUID?.() || (Date.now()+'-'+Math.random()));
        const {data, error} = await sb.rpc(fn, {...params, p_idem_key: idem});
        if(error) throw error;
        toast('✅ Ação executada','success');
        onAction();
      }catch(err){
        toast('Erro: '+(err?.message||'falha'),'error');
        console.error('[Transfer]', fn, err);
      }
      setBusy(false);
    };

    const canApprove = canManage && t.status==='PENDENTE_APROVACAO';
    const canSend = (canManage || isMyFromWh) && t.status==='APROVADA';
    const canReceive = (canManage || isMyToWh) && t.status==='EM_TRANSITO';
    const canResolve = canManage && t.status==='DIVERGENCIA';
    const canCancel = canManage && !['RECEBIDA','CANCELADA'].includes(t.status);

    return (
      <Modal onClose={onClose}>
        <div style={{padding:18,minWidth:480,maxWidth:600}}>
          <h3 style={{margin:'0 0 14px',fontSize:16,fontWeight:700}}>{t.transfer_number} — Detalhes</h3>

          {/* [v224.41 G] TIMELINE com nome+hora embaixo de cada step alcançado */}
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:18,padding:'14px 8px',background:'#FAFAF7',borderRadius:6}}>
            {[
              {step:'PENDENTE_APROVACAO', label:'Solicitada', by:t.requested_by, at:t.requested_at},
              {step:'APROVADA',           label:'Aprovada',   by:t.approved_by,  at:t.approved_at},
              {step:'EM_TRANSITO',        label:'Em trânsito',by:t.sent_by,      at:t.sent_at},
              {step:'RECEBIDA',           label:'Recebida',   by:t.received_by,  at:t.received_at}
            ].map(function(stepInfo, i, arr){
              var step = stepInfo.step;
              var reached = ['PENDENTE_APROVACAO','APROVADA','EM_TRANSITO','RECEBIDA','DIVERGENCIA'].indexOf(t.status) >= i;
              var isCurrent = t.status===step || (step==='RECEBIDA' && t.status==='DIVERGENCIA');
              var hasName = stepInfo.by && reached;
              return (
                <React.Fragment key={step}>
                  <div style={{textAlign:'center',flex:1,minWidth:0}}>
                    <div style={{width:26,height:26,borderRadius:13,background:reached?'#B89840':'#E5E7EB',color:reached?'#fff':'#9CA3AF',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto',fontSize:12,fontWeight:700}}>
                      {i+1}
                    </div>
                    <div style={{fontSize:10,marginTop:5,color:isCurrent?'#1B2A4A':'#6B7280',fontWeight:isCurrent?700:600}}>
                      {stepInfo.label}
                    </div>
                    {hasName && (
                      <div style={{fontSize:9,marginTop:3,color:'#374151',fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:90,margin:'3px auto 0'}}>
                        {uname(stepInfo.by)}
                      </div>
                    )}
                    {hasName && stepInfo.at && (
                      <div style={{fontSize:8.5,marginTop:1,color:'#9CA3AF',fontWeight:500,whiteSpace:'nowrap'}}>
                        {fmtHM(stepInfo.at)}
                      </div>
                    )}
                    {!hasName && reached && (
                      <div style={{fontSize:8.5,marginTop:3,color:'#D1D5DB',fontStyle:'italic'}}>—</div>
                    )}
                  </div>
                  {i<arr.length-1 && <div style={{flex:'0 0 auto',width:24,height:2,background:reached?'#B89840':'#E5E7EB',marginTop:13}}/>}
                </React.Fragment>
              );
            })}
          </div>

          {/* [v224.41 G] Linha extra cancelada/divergência com nome+hora+motivo */}
          {(t.status === 'CANCELADA' && t.cancelled_by) && (
            <div style={{padding:'8px 12px',background:'#FEF2F2',borderRadius:6,marginBottom:14,fontSize:11,color:'#7F1D1D'}}>
              ❌ <strong>Cancelada por {uname(t.cancelled_by)}</strong> em {fmtHM(t.cancelled_at)}
              {t.cancel_reason && <span style={{marginLeft:8,fontStyle:'italic'}}>· "{t.cancel_reason}"</span>}
            </div>
          )}
          {(t.status === 'DIVERGENCIA' && t.divergence_resolved_by) && (
            <div style={{padding:'8px 12px',background:'#FFF7ED',borderRadius:6,marginBottom:14,fontSize:11,color:'#9A3412'}}>
              ⚠️ <strong>Divergência resolvida por {uname(t.divergence_resolved_by)}</strong> em {fmtHM(t.divergence_resolved_at)}
            </div>
          )}

          {/* INFO */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:14,fontSize:12}}>
            <div><span style={{color:'#6B7280'}}>De:</span> <strong>{wname(t.from_warehouse_id)}</strong></div>
            <div><span style={{color:'#6B7280'}}>Para:</span> <strong>{wname(t.to_warehouse_id)}</strong></div>
            <div style={{gridColumn:'span 2'}}><span style={{color:'#6B7280'}}>Produto:</span> <strong>{pname(t.product_id)}</strong></div>
            <div><span style={{color:'#6B7280'}}>Solicitado:</span> <strong>{t.quantity_requested}</strong></div>
            {t.quantity_sent!=null && <div><span style={{color:'#6B7280'}}>Enviado:</span> <strong>{t.quantity_sent}</strong></div>}
            {t.quantity_received!=null && <div><span style={{color:'#6B7280'}}>Recebido:</span> <strong style={{color:t.quantity_received<t.quantity_sent?'#B91C1C':'#15803D'}}>{t.quantity_received}</strong></div>}
            {t.notes && <div style={{gridColumn:'span 2',color:'#374151'}}>📝 {t.notes}</div>}
            {t.divergence_reason && <div style={{gridColumn:'span 2',color:'#B91C1C',background:'#FEE2E2',padding:6,borderRadius:4}}>⚠️ Divergência: {t.divergence_reason}</div>}
            {t.divergence_action && <div style={{gridColumn:'span 2',color:'#374151'}}>✓ Resolvida como <strong>{t.divergence_action}</strong>: {t.divergence_resolution_notes}</div>}
            {t.cancel_reason && <div style={{gridColumn:'span 2',color:'#6B7280'}}>✕ Cancelada: {t.cancel_reason}</div>}
          </div>

          {/* AÇÕES POR STATUS/ROLE */}
          {canApprove && (
            <div style={{padding:12,background:'#FEF3C7',borderRadius:6,marginBottom:10}}>
              <div style={{fontSize:12,marginBottom:8,color:'#78350F'}}>Esta transferência aguarda sua aprovação como admin.</div>
              <button onClick={()=>callRpc('transfer_approve',{p_transfer_id:t.id})} disabled={busy}
                style={{background:'#15803D',color:'#fff',border:'none',padding:'8px 16px',borderRadius:5,fontSize:12,fontWeight:700,cursor:'pointer'}}>
                ✓ Aprovar
              </button>
            </div>
          )}

          {canSend && (
            <div style={{padding:12,background:'#DBEAFE',borderRadius:6,marginBottom:10}}>
              <div style={{fontSize:12,marginBottom:8,color:'#1E3A8A'}}>Confirmar envio físico de <strong>{t.quantity_requested}</strong> unidades. Estoque será debitado de {wname(t.from_warehouse_id)}.</div>
              <button onClick={()=>callRpc('transfer_send',{p_transfer_id:t.id, p_qty_sent:t.quantity_requested})} disabled={busy}
                style={{background:'#1E40AF',color:'#fff',border:'none',padding:'8px 16px',borderRadius:5,fontSize:12,fontWeight:700,cursor:'pointer'}}>
                🚚 Confirmar Envio
              </button>
            </div>
          )}

          {canReceive && (
            <div style={{padding:12,background:'#E0E7FF',borderRadius:6,marginBottom:10}}>
              {/* [v224.46] Aviso explicativo quando peça já vendida (Senador zerado · clamp enviou 0) */}
              {t.quantity_sent === 0 && (
                <div style={{padding:'8px 12px',background:'#FFF7ED',borderRadius:6,marginBottom:8,fontSize:11,color:'#9A3412'}}>
                  📦 Peça já baixada na venda (Senador estava zerado). Recebimento só registra o movimento físico — confirme com <strong>0 un</strong>.
                </div>
              )}
              <div style={{fontSize:12,marginBottom:8,color:'#312E81'}}>Confirmar recebimento. Quantidade enviada: <strong>{t.quantity_sent}</strong>.</div>
              <div style={{display:'flex',gap:8,alignItems:'center',marginBottom:8}}>
                <label style={{fontSize:11,color:'#374151'}}>Recebi:</label>
                <input type="number" min="0" max={t.quantity_sent} value={qtyReceived} onChange={e=>setQtyReceived(e.target.value)}
                  style={{width:80,padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:4,fontSize:13}}/>
              </div>
              {Number(qtyReceived) < Number(t.quantity_sent) && (
                <input type="text" value={divReason} onChange={e=>setDivReason(e.target.value)}
                  placeholder="Motivo da divergência (obrigatório)"
                  style={{width:'100%',padding:'8px 10px',border:'1px solid #B91C1C',borderRadius:4,fontSize:12,marginBottom:8}}/>
              )}
              <button onClick={()=>callRpc('transfer_receive',{p_transfer_id:t.id, p_qty_received:Number(qtyReceived), p_divergence_reason:divReason||null})} disabled={busy || (Number(qtyReceived)<Number(t.quantity_sent) && !divReason.trim())}
                style={{background:'#3730A3',color:'#fff',border:'none',padding:'8px 16px',borderRadius:5,fontSize:12,fontWeight:700,cursor:'pointer'}}>
                ✅ Confirmar Recebimento
              </button>
            </div>
          )}

          {canResolve && (
            <div style={{padding:12,background:'#FEE2E2',borderRadius:6,marginBottom:10}}>
              <div style={{fontSize:12,marginBottom:8,color:'#7F1D1D'}}>Resolver divergência (faltou {t.quantity_sent - t.quantity_received} unidades):</div>
              <select value={divAction} onChange={e=>setDivAction(e.target.value)}
                style={{width:'100%',padding:'7px 10px',border:'1px solid #D1D5DB',borderRadius:4,fontSize:12,marginBottom:8}}>
                <option value="PERDA">PERDA — sumiu, baixa definitiva</option>
                <option value="AVARIA">AVARIA — produto danificado</option>
                <option value="DEVOLVIDO_ORIGEM">DEVOLVIDO ORIGEM — voltou pro depósito de origem</option>
              </select>
              <input type="text" value={divNotes} onChange={e=>setDivNotes(e.target.value)}
                placeholder="Justificativa (mín 5 chars, obrigatória)"
                style={{width:'100%',padding:'8px 10px',border:'1px solid #D1D5DB',borderRadius:4,fontSize:12,marginBottom:8}}/>
              <button onClick={()=>callRpc('transfer_resolve_divergence',{p_transfer_id:t.id, p_action:divAction, p_resolution_notes:divNotes})} disabled={busy || divNotes.trim().length<5}
                style={{background:'#991B1B',color:'#fff',border:'none',padding:'8px 16px',borderRadius:5,fontSize:12,fontWeight:700,cursor:'pointer'}}>
                ✓ Resolver
              </button>
            </div>
          )}

          {canCancel && (
            <details style={{marginBottom:10}}>
              <summary style={{cursor:'pointer',fontSize:12,color:'#6B7280'}}>✕ Cancelar transferência</summary>
              <div style={{padding:12,background:'#F3F4F6',borderRadius:6,marginTop:6}}>
                <input type="text" value={cancelReason} onChange={e=>setCancelReason(e.target.value)}
                  placeholder="Motivo (mín 5 chars)"
                  style={{width:'100%',padding:'7px 10px',border:'1px solid #D1D5DB',borderRadius:4,fontSize:12,marginBottom:8}}/>
                <button onClick={()=>callRpc('transfer_cancel',{p_transfer_id:t.id, p_reason:cancelReason})} disabled={busy || cancelReason.trim().length<5}
                  style={{background:'#6B7280',color:'#fff',border:'none',padding:'7px 14px',borderRadius:4,fontSize:11,fontWeight:600,cursor:'pointer'}}>
                  Cancelar
                </button>
              </div>
            </details>
          )}

          <div style={{display:'flex',justifyContent:'flex-end',marginTop:14}}>
            <button onClick={onClose} style={{padding:'8px 16px',border:'1px solid #D1D5DB',background:'#fff',borderRadius:5,cursor:'pointer',fontSize:12}}>Fechar</button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.depositos = window.ZNX.widgets.depositos || {};
  window.ZNX.widgets.depositos.TransferDetailModal = TransferDetailModal;
})();
