// js/components/pages/ReceberTransferencia.jsx
// [v224.31 FEATURE 20260526] Page dedicada estoquistas (Ibra/Abbes/Munir) verem transferências
// pendentes em UMA tela única · sem precisar abrir Depósitos/Entradas.
// Decisão Jamal: P1=B nova page · P2=d filter ≠RECEBIDA/CANCELADA · P3=a badge animation · P4=a global.
// Reuso: TransferDetailModal (callback onAction · v224.30 já liberou estoquista workflow approve/cancel/resolve).
(function() {
  'use strict';
  const {useState, useEffect, useMemo, useCallback} = React;

  function ReceberTransferencia({user, products, allUsers, onTransferReceived}) {
    const sb = window.sb;
    const TDM = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.depositos && window.ZNX.widgets.depositos.TransferDetailModal;
    if (!TDM) {
      const _msg = '[ReceberTransferencia] TransferDetailModal missing — verifique carregamento Depositos widgets';
      console.error(_msg);
      if (window.Sentry) window.Sentry.captureMessage(_msg, 'error');
    }

    const [transfers, setTransfers] = useState([]);
    const [warehouses, setWarehouses] = useState([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter] = useState('Todos');
    const [selectedTransfer, setSelectedTransfer] = useState(null);

    const reload = useCallback(function(){
      setLoading(true);
      Promise.all([
        sb.from('warehouses').select('id,name,code,manager_app_user_id').order('name'),
        sb.from('stock_transfers').select('*').not('status','in','("RECEBIDA","CANCELADA")').order('created_at',{ascending:false})
      ]).then(function(results){
        var whRes = results[0]; var trRes = results[1];
        if (whRes.error) console.warn('[ReceberTransferencia] warehouses fetch failed:', whRes.error.message);
        if (trRes.error) console.warn('[ReceberTransferencia] transfers fetch failed:', trRes.error.message);
        setWarehouses(whRes.data || []);
        setTransfers(trRes.data || []);
        setLoading(false);
      }).catch(function(e){
        console.error('[ReceberTransferencia] reload failed:', e);
        setLoading(false);
      });
    }, []);

    useEffect(function(){
      reload();
      // [v224.74] lib hardened com fallback raw
      const handle = window.ZNX && window.ZNX.lib && window.ZNX.lib.realtime
        ? window.ZNX.lib.realtime.subscribe('stock_transfers', function(){ reload(); })
        : (function(){
            const ch = sb.channel('znx-receber-transf-page')
              .on('postgres_changes', {event:'*', schema:'public', table:'stock_transfers'}, reload)
              .subscribe();
            return { _ch: ch, _fallback: true };
          })();
      return function(){
        if(handle && handle._fallback) sb.removeChannel(handle._ch);
        else if(handle && window.ZNX?.lib?.realtime) window.ZNX.lib.realtime.unsubscribe(handle);
      };
    }, [reload]);

    const statusMap = {
      'Aguardando Aprovação': 'PENDENTE_APROVACAO',
      'Aguardando Envio': 'APROVADA',
      'Em Trânsito': 'EM_TRANSITO',
      'Divergência': 'DIVERGENCIA'
    };

    const filtered = useMemo(function(){
      if (filter === 'Todos') return transfers;
      return transfers.filter(function(t){ return t.status === statusMap[filter]; });
    }, [transfers, filter]);

    function getWhName(id){
      const w = warehouses.find(function(x){ return x.id === id; });
      return w ? w.name : '—';
    }
    function getProductName(id){
      const p = (products||[]).find(function(x){ return x.id === id; });
      return p ? ((p.brand||'') + ' ' + (p.name||'')).trim() : '—';
    }
    function statusBadge(status){
      const map = {
        'PENDENTE_APROVACAO': {bg:'#FEF3C7', fg:'#92400E', label:'Aguardando Aprovação'},
        'APROVADA':           {bg:'#DBEAFE', fg:'#1E40AF', label:'Aprovada · Aguardando Envio'},
        'EM_TRANSITO':        {bg:'#E0E7FF', fg:'#3730A3', label:'Em Trânsito'},
        'DIVERGENCIA':        {bg:'#FEE2E2', fg:'#991B1B', label:'⚠️ Divergência'}
      };
      const s = map[status] || {bg:'#F3F4F6', fg:'#374151', label:status};
      return <span style={{padding:'3px 10px',borderRadius:999,fontSize:11,fontWeight:600,background:s.bg,color:s.fg}}>{s.label}</span>;
    }

    return (
      <div style={{padding:'4px',minHeight:'100vh'}}>
        <div style={{marginBottom:20}}>
          <h2 style={{fontSize:24,fontWeight:700,color:'#111827',margin:0}}>🔄 Receber Transferência</h2>
          <div style={{fontSize:13,color:'#6B7280',marginTop:4}}>
            {transfers.length} transferência{transfers.length!==1?'s':''} aguardando ação
          </div>
        </div>

        <div style={{display:'flex',gap:6,marginBottom:16,flexWrap:'wrap'}}>
          {['Todos','Aguardando Aprovação','Aguardando Envio','Em Trânsito','Divergência'].map(function(f){
            const active = filter === f;
            return (
              <button key={f} onClick={function(){ setFilter(f); }}
                style={{
                  padding:'6px 14px',fontSize:12,
                  border:'1px solid '+(active?'#B89840':'#E5E7EB'),
                  background:active?'#FEF3C7':'#fff',
                  color:active?'#92400E':'#6B7280',
                  borderRadius:8,cursor:'pointer',fontWeight:600
                }}>
                {f}
              </button>
            );
          })}
        </div>

        {loading ? (
          <div style={{padding:30,textAlign:'center',color:'#6B7280'}}>Carregando...</div>
        ) : filtered.length === 0 ? (
          <div style={{padding:50,textAlign:'center',color:'#9CA3AF',background:'#fff',borderRadius:12,border:'1px solid #E5E7EB'}}>
            🎉 Nenhuma transferência {filter==='Todos'?'pendente':'nesta categoria'}!
          </div>
        ) : (
          <div style={{background:'#fff',borderRadius:12,border:'1px solid #E5E7EB',overflow:'auto'}}>
            <table style={{width:'100%',fontSize:13,borderCollapse:'collapse'}}>
              <thead style={{background:'#F9FAFB'}}>
                <tr style={{borderBottom:'2px solid #E5E7EB',color:'#6B7280',fontSize:11}}>
                  <th style={{textAlign:'left',padding:'12px 14px',fontWeight:600}}>N°</th>
                  <th style={{textAlign:'left',padding:'12px 14px',fontWeight:600}}>Rota</th>
                  <th style={{textAlign:'left',padding:'12px 14px',fontWeight:600}}>Produto</th>
                  <th style={{textAlign:'right',padding:'12px 14px',fontWeight:600}}>Qty</th>
                  <th style={{textAlign:'center',padding:'12px 14px',fontWeight:600}}>Status</th>
                  <th style={{textAlign:'right',padding:'12px 14px',fontWeight:600}}>Solicitada</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(function(t){
                  return (
                    <tr key={t.id} onClick={function(){ setSelectedTransfer(t); }}
                      style={{borderBottom:'1px solid #F3F4F6',cursor:'pointer',transition:'background 0.15s'}}
                      onMouseEnter={function(e){ e.currentTarget.style.background='#F9FAFB'; }}
                      onMouseLeave={function(e){ e.currentTarget.style.background='#fff'; }}>
                      <td style={{padding:'12px 14px',fontWeight:600,color:'#1B2A4A'}}>{t.transfer_number}</td>
                      <td style={{padding:'12px 14px',color:'#6B7280'}}>
                        {getWhName(t.from_warehouse_id)} → <strong style={{color:'#1B2A4A'}}>{getWhName(t.to_warehouse_id)}</strong>
                      </td>
                      <td style={{padding:'12px 14px',color:'#374151'}}>{getProductName(t.product_id)}</td>
                      <td style={{padding:'12px 14px',textAlign:'right',fontWeight:700,fontSize:14}}>{t.quantity_requested}</td>
                      <td style={{padding:'12px 14px',textAlign:'center'}}>{statusBadge(t.status)}</td>
                      <td style={{padding:'12px 14px',textAlign:'right',color:'#6B7280',fontSize:11}}>
                        {new Date(t.requested_at || t.created_at).toLocaleDateString('pt-BR')}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {selectedTransfer && TDM && (
          <TDM
            transfer={selectedTransfer}
            user={user}
            warehouses={warehouses}
            products={products}
            allUsers={allUsers}
            onClose={function(){ setSelectedTransfer(null); }}
            onAction={function(){
              setSelectedTransfer(null);
              reload();
              if (typeof onTransferReceived === 'function') onTransferReceived();
            }}
          />
        )}
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.ReceberTransferencia = ReceberTransferencia;
  window.ReceberTransferencia = ReceberTransferencia;
})();
