// js/components/widgets/entradas/EntradasListPanel.jsx
// [Wave 23 v224.4 NUCLEAR] Aba "Entradas" — stats + filtros + tabela grouped/flat
// Extraído de pages/Entradas.jsx L805-1003 (literal)
//
// Deps runtime globals: nid, fmt, fmtDate, W_ALFONSO (via calcs)
(function(){
  'use strict';

  // [v224.73 + v224.55] vars MOVED to component body
  function EntradasListPanel(props){
    const calcs = window.ZNX && window.ZNX.entradas && window.ZNX.entradas.calcs;
    const W_ALFONSO = (calcs && calcs.W_ALFONSO) || '507c0241-6ee7-491a-bc6c-aab8e4d630d8';
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    const fmtDate = window.fmtDate || function(d){return d||'—';};

    const {entries, filteredEntries, groupedByDay, monthStats,
      suppliers, products, notasFreteiro, warehouseName,
      searchTerm, setSearchTerm, filterSupplier, setFilterSupplier,
      filterDateFrom, setFilterDateFrom, filterDateTo, setFilterDateTo,
      showVoided, setShowVoided, groupByDay, setGroupByDay,
      sortBy, setSortBy, canSeeCost, isAdmin, user,
      onVoidClick, onDetailClick, onOpenNota, setTab} = props;
    // [v224.27 ESTOQUISTA-PRIVACY 20260526] gate fornecedor via window.canSeeSupplier
    const canSeeSupplier = (typeof window!=='undefined' && window.canSeeSupplier) ? window.canSeeSupplier(user) : true;

    function clearFilters(){
      setSearchTerm(''); setFilterSupplier(''); setFilterDateFrom(''); setFilterDateTo(''); setShowVoided(false);
    }

    function renderEntryRow(e){
      const p = (products||[]).find(function(x){return typeof nid==='function' ? nid(x.id, e.productId) : String(x.id)===String(e.productId);});
      const s = (suppliers||[]).find(function(x){return x.id===e.supplierId;});
      const nf = e.notaFreteiroId ? (notasFreteiro||[]).find(function(n){return n.id===e.notaFreteiroId;}) : null;
      const ts = e.createdAt||e.created_at||e.date;
      const d = ts ? new Date(ts) : null;
      const horaStr = d&&!isNaN(d) ? d.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}) : '—';
      const dataStr = d&&!isNaN(d) ? d.toLocaleDateString('pt-BR') : (e.date?fmtDate(e.date):'—');
      return (
        <tr key={e.id} onClick={function(){onDetailClick && onDetailClick(e.id);}}
          style={Object.assign({cursor:'pointer'}, e.isVoid?{opacity:0.55,background:'#FEF2F2'}:{})}
          title="Clique pra ver histórico completo desta entrada">
          <td>
            <div style={{fontWeight:600,fontSize:13}}>{dataStr}</div>
            <div style={{fontSize:11,color:'#6B7280',marginTop:2}}>🕐 {horaStr}</div>
          </td>
          <td style={{fontWeight:500}}>{e.isVoid && <span style={{fontSize:10,background:'#DC2626',color:'#fff',padding:'1px 6px',borderRadius:4,marginRight:6}}>CANCELADA</span>}{(p && p.name)||'—'}</td>
          {canSeeSupplier && <td className="dim">{(s && s.name)||'—'}</td>}
          <td>{(function(){
            const wid = e.warehouseId || e.warehouse_id;
            if(!wid) return <span className="dim" style={{fontSize:12}}>—</span>;
            const isPrincipal = wid===W_ALFONSO;
            const bg = isPrincipal ? '#FEF3C7' : '#DBEAFE';
            const fg = isPrincipal ? '#92400E' : '#1E40AF';
            return <span style={{background:bg,color:fg,borderRadius:5,padding:'2px 8px',fontSize:11,fontWeight:600}}>{warehouseName(wid)}</span>;
          })()}</td>
          <td>{nf ?
            <span style={{background:'#EFF6FF',color:'#2563EB',borderRadius:5,padding:'2px 8px',fontSize:11,fontWeight:600,cursor:'pointer'}} onClick={function(ev){ev.stopPropagation(); onOpenNota && onOpenNota(nf); setTab && setTab('notas');}}>{nf.number} · {nf.freteiro}</span>
            : <span className="dim" style={{fontSize:12}}>—</span>}</td>
          <td>{e.qty}</td>
          {canSeeCost && <td className="gold">{fmt(e.unitCost)}</td>}
          {canSeeCost && <td style={{fontWeight:600}}>{fmt(e.qty*e.unitCost)}</td>}
          <td className="dim" style={{fontSize:12}}>{e.createdBy||e.created_by_name||'—'}</td>
          <td className="dim">{e.isVoid ? <span style={{color:'#DC2626',fontSize:11}}>{e.voidReason||e.void_reason||'cancelada'}</span> : (e.notes||'—')}</td>
          {isAdmin && (
            <td style={{textAlign:'center'}}>
              {!e.isVoid && (
                <button onClick={function(ev){ev.stopPropagation(); onVoidClick && onVoidClick(e, (p && p.name)||'produto');}}
                  title="Cancelar entrada (reverte estoque)"
                  style={{background:'transparent',border:'1px solid #DC2626',color:'#DC2626',padding:'4px 10px',borderRadius:5,fontSize:11,fontWeight:600,cursor:'pointer'}}>🗑 Cancelar</button>
              )}
            </td>
          )}
        </tr>
      );
    }

    return (
      <>
        {/* Cards totalizadores mensais */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:12,marginBottom:14}}>
          <div className="card" style={{padding:14,background:'linear-gradient(135deg,#1B2A4A 0%,#2A3F6E 100%)',color:'#fff'}}>
            <div style={{fontSize:11,opacity:0.75,fontWeight:600,textTransform:'uppercase',letterSpacing:0.5}}>Este mês</div>
            <div style={{fontSize:28,fontWeight:800,marginTop:4,color:'#B89840'}}>{monthStats.count}</div>
            <div style={{fontSize:11,opacity:0.85,marginTop:2}}>entradas registradas</div>
          </div>
          <div className="card" style={{padding:14}}>
            <div style={{fontSize:11,color:'#6B7280',fontWeight:600,textTransform:'uppercase',letterSpacing:0.5}}>Unidades entradas</div>
            <div style={{fontSize:24,fontWeight:700,marginTop:4,color:'#1B2A4A'}}>{monthStats.totalQty.toLocaleString('pt-BR')}</div>
            <div style={{fontSize:11,color:'#9CA3AF',marginTop:2}}>no mês</div>
          </div>
          {canSeeCost && (
            <div className="card" style={{padding:14,background:'linear-gradient(135deg,#FEF3C7 0%,#FDE68A 100%)'}}>
              <div style={{fontSize:11,color:'#92400E',fontWeight:600,textTransform:'uppercase',letterSpacing:0.5}}>Investido (custo)</div>
              <div style={{fontSize:22,fontWeight:800,marginTop:4,color:'#92400E'}}>{fmt(monthStats.totalValue)}</div>
              <div style={{fontSize:11,color:'#A16207',marginTop:2}}>em produto este mês</div>
            </div>
          )}
        </div>

        {/* Barra de filtros */}
        <div className="card" style={{padding:12,marginBottom:14,display:'flex',gap:10,flexWrap:'wrap',alignItems:'center'}}>
          <div style={{flex:'1 1 220px',position:'relative'}}>
            <input type="text" value={searchTerm} onChange={function(e){setSearchTerm(e.target.value);}}
              placeholder="🔍 Buscar produto, fornecedor, obs..."
              style={{width:'100%',padding:'8px 12px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13}}/>
          </div>
          {/* [v224.27 ESTOQUISTA-PRIVACY 20260526] esconde filter fornecedor pra estoquista */}
          {canSeeSupplier && (
            <select value={filterSupplier} onChange={function(e){setFilterSupplier(e.target.value);}}
              style={{padding:'8px 10px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13,background:'#fff'}}>
              <option value="">Todos fornecedores</option>
              {(suppliers||[]).map(function(s){return <option key={s.id} value={s.id}>{s.name}</option>;})}
            </select>
          )}
          <input type="date" value={filterDateFrom} onChange={function(e){setFilterDateFrom(e.target.value);}} title="De"
            style={{padding:'7px 10px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13}}/>
          <span style={{color:'#9CA3AF',fontSize:13}}>até</span>
          <input type="date" value={filterDateTo} onChange={function(e){setFilterDateTo(e.target.value);}} title="Até"
            style={{padding:'7px 10px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13}}/>
          <select value={sortBy} onChange={function(e){setSortBy(e.target.value);}}
            style={{padding:'8px 10px',border:'1px solid #E4E7EC',borderRadius:6,fontSize:13,background:'#fff'}}>
            <option value="date_desc">Mais recentes</option>
            <option value="date_asc">Mais antigas</option>
            <option value="qty_desc">Maior qtd</option>
            <option value="qty_asc">Menor qtd</option>
            {canSeeCost && <option value="total_desc">Maior valor</option>}
          </select>
          <label style={{display:'flex',alignItems:'center',gap:6,fontSize:12,color:'#374151',cursor:'pointer',padding:'6px 10px',border:'1px solid #E4E7EC',borderRadius:6,background:groupByDay?'#EFF6FF':'#fff'}}>
            <input type="checkbox" checked={groupByDay} onChange={function(e){setGroupByDay(e.target.checked);}} style={{cursor:'pointer'}}/>
            Agrupar por dia
          </label>
          {isAdmin && (
            <label style={{display:'flex',alignItems:'center',gap:6,fontSize:12,color:'#374151',cursor:'pointer',padding:'6px 10px',border:'1px solid #E4E7EC',borderRadius:6,background:showVoided?'#FEF2F2':'#fff'}}>
              <input type="checkbox" checked={showVoided} onChange={function(e){setShowVoided(e.target.checked);}} style={{cursor:'pointer'}}/>
              🗑 Ver canceladas
            </label>
          )}
          {(searchTerm||filterSupplier||filterDateFrom||filterDateTo||showVoided) && (
            <button onClick={clearFilters}
              style={{padding:'6px 12px',background:'transparent',border:'1px solid #DC2626',color:'#DC2626',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer'}}>✕ Limpar</button>
          )}
          <div style={{marginLeft:'auto',fontSize:12,color:'#6B7280',fontWeight:600}}>
            {filteredEntries.length} {filteredEntries.length===1?'entrada':'entradas'}
          </div>
        </div>

        {/* Tabela */}
        <div className="card" style={{padding:0}}>
          <table>
            <thead><tr>
              <th>Data / Hora</th>
              <th>Produto</th>
              {canSeeSupplier && <th>Fornecedor</th>}
              <th>Depósito</th>
              <th>Nota Freteiro</th>
              <th>Qtd</th>
              {canSeeCost && <th>Custo Unit.</th>}
              {canSeeCost && <th>Total</th>}
              <th>Registrado por</th>
              <th>Obs.</th>
              {isAdmin && <th style={{width:60,textAlign:'center'}}>Ações</th>}
            </tr></thead>
            <tbody>
              {groupByDay && groupedByDay && groupedByDay.length>0 && groupedByDay.map(function(group){
                return (
                  <React.Fragment key={group.date}>
                    <tr style={{background:'#F8FAFC'}}>
                      <td colSpan={7+(canSeeSupplier?1:0)+(canSeeCost?2:0)+(isAdmin?1:0)} style={{padding:'10px 14px',fontWeight:700,fontSize:12,color:'#1B2A4A',borderTop:'2px solid #E4E7EC'}}>
                        📅 {group.date}
                        <span style={{marginLeft:12,color:'#6B7280',fontWeight:500}}>· {group.entries.length} entrada{group.entries.length>1?'s':''}</span>
                        <span style={{marginLeft:8,color:'#6B7280',fontWeight:500}}>· {group.totalQty} un.</span>
                        {canSeeCost && <span style={{marginLeft:8,color:'#92400E',fontWeight:600}}>· {fmt(group.totalValue)}</span>}
                      </td>
                    </tr>
                    {group.entries.map(renderEntryRow)}
                  </React.Fragment>
                );
              })}
              {!groupByDay && filteredEntries.map(renderEntryRow)}
              {filteredEntries.length===0 && (
                <tr><td colSpan={7+(canSeeSupplier?1:0)+(canSeeCost?2:0)+(isAdmin?1:0)} style={{textAlign:'center',color:'#9CA3AF',padding:40}}>
                  {(searchTerm||filterSupplier||filterDateFrom||filterDateTo||showVoided)
                    ? <>Nenhuma entrada bate com os filtros aplicados. <button onClick={clearFilters} style={{background:'none',border:'none',color:'#2563EB',fontWeight:600,cursor:'pointer',textDecoration:'underline'}}>Limpar filtros</button></>
                    : <>Nenhuma entrada registrada. Clique em <strong>+ Registrar Entrada</strong> para começar.</>}
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </>
    );
  }

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