// js/components/widgets/AjusteEstoqueRapidoModal.jsx
// [v223.36 FEAT-STOCK-ADMIN 20260520] Modal ajuste RÁPIDO estoque admin Jamal (botão 🔧 linha Produtos)
// Backend: warehouse_stock_adjust RPC (FOR UPDATE + bypass quádruplo + log_admin_action)
// Aplica regra_invariante_products_stock_via_pws_only (via pws, nunca products.stock direto)
//
// NOTA — coexiste com widgets/depositos/AjusteEstoqueModal.jsx (multi-produto search Depósitos>Inventário).
// Renomeado p/ "Rapido" pra distinguir: este é quick-adjust 1-produto na linha Produtos.
//
// Props:
//   product ({id, name, stock}) — produto da linha clicada
//   onClose () — callback fechar modal
//   onSuccess () — callback após save com sucesso
// Deps runtime: window.sb (supabase) · window.Modal · window.fmt · window.toast · window.Sentry (opcional)
(function(){
  'use strict';
  const {useState, useEffect} = React;

  const WAREHOUSE_ALFONSO = '507c0241-6ee7-491a-bc6c-aab8e4d630d8';
  const WAREHOUSE_SENADOR = '05a89051-be3e-48e2-8ed0-c7674b72d97a';

  function AjusteEstoqueRapidoModal(props){
    const { product, onClose, onSuccess } = props;
    const Modal = window.Modal;
    const toast = window.toast || ((m)=>console.log('[toast]', m));
    const sb = window.sb;

    const [loading, setLoading] = useState(true);
    const [alfonsoQty, setAlfonsoQty] = useState(0);
    const [senadorQty, setSenadorQty] = useState(0);
    const [selectedWarehouse, setSelectedWarehouse] = useState(WAREHOUSE_ALFONSO);
    const [newQty, setNewQty] = useState('');
    const [reason, setReason] = useState('');
    const [inFlight, setInFlight] = useState(false);

    // [regra_validacao_helpers_runtime] Fail-loud sb não disponível
    useEffect(()=>{
      if (typeof sb?.from !== 'function') {
        console.error('[ZNX v223.36] AjusteEstoqueRapidoModal: window.sb não disponível');
        toast('❌ Erro: cliente Supabase não carregou', 'error');
        onClose();
        return;
      }
      (async () => {
        try {
          const { data, error } = await sb.from('product_warehouse_stock')
            .select('warehouse_id, quantity')
            .eq('product_id', product.id);
          if (error) throw error;
          let alf = 0, sen = 0;
          (data||[]).forEach(row => {
            if (row.warehouse_id === WAREHOUSE_ALFONSO) alf = Number(row.quantity)||0;
            if (row.warehouse_id === WAREHOUSE_SENADOR) sen = Number(row.quantity)||0;
          });
          setAlfonsoQty(alf);
          setSenadorQty(sen);
          setNewQty(String(alf)); // padrão Alfonso (principal)
          setLoading(false);
        } catch(e) {
          console.error('[ZNX v223.36] erro buscar pws:', e);
          toast('❌ Erro buscar estoque atual: '+(e?.message||'desconhecido'), 'error');
          window.Sentry?.captureException?.(e, { tags: { ctx: 'v223.36 ajuste-estoque-load' } });
          onClose();
        }
      })();
    },[product.id]);

    // Quando troca depósito, atualiza newQty pro estoque atual desse depósito
    function handleWarehouseChange(whId){
      setSelectedWarehouse(whId);
      const currentQty = whId === WAREHOUSE_ALFONSO ? alfonsoQty : senadorQty;
      setNewQty(String(currentQty));
    }

    const currentQty = selectedWarehouse === WAREHOUSE_ALFONSO ? alfonsoQty : senadorQty;
    const newQtyNum = parseInt(newQty, 10);
    const isValidQty = !isNaN(newQtyNum) && newQtyNum >= 0;
    const isValidReason = reason.trim().length >= 5;
    const isDifferent = isValidQty && newQtyNum !== currentQty;
    const canSave = !inFlight && !loading && isValidQty && isValidReason && isDifferent;

    async function handleSave(){
      if (!canSave) return;
      setInFlight(true);
      try {
        const idemKey = (window.crypto?.randomUUID?.()) || (Date.now()+'-'+Math.random());
        const { data, error } = await sb.rpc('warehouse_stock_adjust', {
          p_product_id: product.id,
          p_warehouse_id: selectedWarehouse,
          p_new_qty: newQtyNum,
          p_reason: reason.trim(),
          p_idem_key: idemKey
        });
        if (error) throw error;
        const result = data || {};
        const whName = selectedWarehouse === WAREHOUSE_ALFONSO ? 'Alfonso' : 'Senador';
        const diff = (result.diff>=0?'+':'') + result.diff;
        toast(`✅ Estoque ajustado: ${whName} de ${result.old} → ${result.new} un (${diff})`, 'success');
        onSuccess();
      } catch(e) {
        console.error('[ZNX v223.36] erro RPC warehouse_stock_adjust:', e);
        const msg = e?.message || 'erro desconhecido';
        toast('❌ Erro ajustar estoque: '+msg, 'error');
        window.Sentry?.captureException?.(e, {
          tags: { ctx: 'v223.36 ajuste-estoque-save' },
          extra: { product_id: product.id, warehouse_id: selectedWarehouse, new_qty: newQtyNum }
        });
        setInFlight(false);
      }
    }

    if (!Modal) {
      console.error('[ZNX v223.36] window.Modal não disponível');
      return null;
    }

    return (
      <Modal title={`🔧 Ajustar estoque — ${product.name}`} onClose={onClose}>
        {loading ? (
          <div style={{padding:30,textAlign:'center',color:'#6B7280'}}>Carregando estoque atual...</div>
        ) : (
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            {/* Aviso ⚠️ */}
            <div style={{padding:'10px 14px',background:'#FEF3C7',border:'1px solid #C8A95155',borderRadius:8,fontSize:12,color:'#92400E'}}>
              ⚠️ Ajuste estoque físico via depósito. Operação fica registrada em audit log (admin_audit_log) com motivo informado.
            </div>

            {/* Grid 2 depósitos */}
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
              <label style={{padding:14,border:'2px solid '+(selectedWarehouse===WAREHOUSE_ALFONSO?'#7C3AED':'#E5E7EB'),borderRadius:8,cursor:'pointer',background:selectedWarehouse===WAREHOUSE_ALFONSO?'#F5F3FF':'#FFFFFF'}}>
                <input type="radio" name="wh" checked={selectedWarehouse===WAREHOUSE_ALFONSO}
                  onChange={()=>handleWarehouseChange(WAREHOUSE_ALFONSO)} style={{marginRight:8}}/>
                <strong style={{fontSize:14,color:'#1B2A4A'}}>Alfonso</strong>
                <span style={{fontSize:10,color:'#7C3AED',marginLeft:6,fontWeight:600}}>PRINCIPAL</span>
                <div style={{fontSize:24,fontWeight:800,color:'#1B2A4A',marginTop:4}}>{alfonsoQty} un</div>
                <div style={{fontSize:10,color:'#9CA3AF'}}>estoque atual</div>
              </label>
              <label style={{padding:14,border:'2px solid '+(selectedWarehouse===WAREHOUSE_SENADOR?'#7C3AED':'#E5E7EB'),borderRadius:8,cursor:'pointer',background:selectedWarehouse===WAREHOUSE_SENADOR?'#F5F3FF':'#FFFFFF'}}>
                <input type="radio" name="wh" checked={selectedWarehouse===WAREHOUSE_SENADOR}
                  onChange={()=>handleWarehouseChange(WAREHOUSE_SENADOR)} style={{marginRight:8}}/>
                <strong style={{fontSize:14,color:'#1B2A4A'}}>Senador</strong>
                <div style={{fontSize:24,fontWeight:800,color:'#1B2A4A',marginTop:4}}>{senadorQty} un</div>
                <div style={{fontSize:10,color:'#9CA3AF'}}>estoque atual</div>
              </label>
            </div>

            {/* Input nova qty */}
            <div>
              <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>
                Nova quantidade ({selectedWarehouse===WAREHOUSE_ALFONSO?'Alfonso':'Senador'})
              </label>
              <input type="number" min="0" step="1"
                value={newQty}
                onChange={e=>setNewQty(e.target.value)}
                placeholder={String(currentQty)}
                style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:18,fontWeight:700,textAlign:'center'}}
                autoFocus/>
              {isValidQty && isDifferent && (
                <div style={{fontSize:11,color:newQtyNum>currentQty?'#16A34A':'#DC2626',marginTop:4,textAlign:'center'}}>
                  {newQtyNum>currentQty?'+':''}{newQtyNum-currentQty} unidades ({newQtyNum>currentQty?'adicionar':'remover'})
                </div>
              )}
            </div>

            {/* Motivo obrigatório */}
            <div>
              <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>
                Motivo do ajuste <span style={{color:'#DC2626'}}>(obrigatório · min 5 chars)</span>
              </label>
              <input type="text"
                value={reason}
                onChange={e=>setReason(e.target.value)}
                placeholder="Ex: Encontradas 3 unidades no fundo do depósito Alfonso"
                maxLength={200}
                style={{width:'100%',padding:'10px 12px',border:'1px solid '+(reason.length>=5?'#16A34A':'#D1D5DB'),borderRadius:6,fontSize:13}}/>
              <div style={{fontSize:10,color:'#9CA3AF',marginTop:2,textAlign:'right'}}>{reason.length}/200</div>
            </div>

            {/* Botões */}
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:6}}>
              <button onClick={onClose} disabled={inFlight}
                style={{padding:'10px 20px',background:'#FFFFFF',color:'#374151',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14,fontWeight:600,cursor:inFlight?'not-allowed':'pointer',opacity:inFlight?0.5:1}}>
                Cancelar
              </button>
              <button onClick={handleSave} disabled={!canSave}
                style={{padding:'10px 20px',background:canSave?'#7C3AED':'#9CA3AF',color:'#FFFFFF',border:'none',borderRadius:6,fontSize:14,fontWeight:700,cursor:canSave?'pointer':'not-allowed'}}>
                {inFlight?'💾 Salvando...':'💾 Salvar ajuste'}
              </button>
            </div>
          </div>
        )}
      </Modal>
    );
  }

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