// js/components/widgets/EditUserModal.jsx
// Admin edita nome + role + ativar/desativar de qualquer user.
// Chama admin_update_user (nome+role) e admin_toggle_user_active (ativo).
// Onda C+ V2 — 2026-05-06.
(function() {
  'use strict';
  const {useState, useEffect} = React;

  function EditUserModal({user, target, onClose, onSuccess}){
    const[name,setName]=useState('');
    const[role,setRole]=useState('vendedor');
    const[active,setActive]=useState(true);
    const[loading,setLoading]=useState(false);

    useEffect(()=>{
      if(target){
        setName(target.name||'');
        setRole(target.role||'vendedor');
        setActive(target.active!==false);
      }
    },[target]);

    if(!target)return null;

    const isSelf = target.auth_user_id === user.auth_user_id;
    const nameChanged = name.trim() !== (target.name||'');
    const roleChanged = role !== (target.role||'');
    const activeChanged = active !== (target.active!==false);
    const hasChanges = nameChanged || roleChanged || activeChanged;

    async function handleSave(){
      if(loading)return;
      if(!hasChanges){toast('Nada mudou','warning');return;}
      if(!name.trim() || name.trim().length<2){toast('⚠️ Nome obrigatório (min 2 chars)','warning');return;}
      if(isSelf && role!=='admin'){toast('⚠️ Não pode tirar sua própria role admin','warning');return;}
      if(isSelf && !active){toast('⚠️ Não pode desativar a própria conta','warning');return;}

      setLoading(true);
      try {
        // 1) Update name + role (uma RPC só)
        if(nameChanged || roleChanged){
          const{error:err1}=await sb.rpc('admin_update_user',{
            p_target_user_id: target.auth_user_id,
            p_name: name.trim(),
            p_role: role
          });
          if(err1){
            toast('❌ Erro ao atualizar: '+err1.message,'error');
            setLoading(false);return;
          }
        }
        // 2) Toggle active (RPC separada — atomicidade por op)
        if(activeChanged){
          const{error:err2}=await sb.rpc('admin_toggle_user_active',{
            p_target_user_id: target.auth_user_id,
            p_active: active
          });
          if(err2){
            toast('❌ Erro ao alterar status: '+err2.message,'error');
            setLoading(false);return;
          }
        }
        let msg='✅ '+name.trim()+' atualizado.';
        if(roleChanged) msg+=' Role mudou — usuário foi deslogado.';
        else if(activeChanged && !active) msg+=' Usuário desativado e deslogado.';
        toast(msg);
        if(typeof onSuccess==='function')onSuccess({nameChanged,roleChanged,activeChanged});
        onClose();
      } catch(e){
        toast('❌ Erro inesperado: '+(e?.message||'desconhecido'),'error');
      } finally {
        setLoading(false);
      }
    }

    return(
      <Modal title={'✏️ Editar — '+(target.name||'?')} onClose={onClose}>
        <div style={{display:'flex',flexDirection:'column',gap:14}}>
          <div>
            <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>Nome completo</label>
            <input
              type="text"
              value={name}
              onChange={e=>setName(e.target.value)}
              placeholder="Nome do usuário"
              style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14}}
              autoFocus
              disabled={loading}
            />
          </div>

          <div>
            <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>Role / Permissão</label>
            <select value={role} onChange={e=>setRole(e.target.value)} disabled={loading||isSelf} style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14,background:'#FFFFFF'}}>
              <option value="admin">👑 Admin (acesso total)</option>
              <option value="financeiro">💰 Financeiro</option>
              <option value="vendedor">📞 Vendedor</option>
              <option value="estoquista">📦 Estoquista</option>
            </select>
            {isSelf && <div style={{fontSize:10,color:'#EA580C',marginTop:3}}>⚠️ Você não pode mudar sua própria role (peça pra outro admin)</div>}
            {roleChanged && !isSelf && <div style={{fontSize:10,color:'#EA580C',marginTop:3}}>⚠️ Mudar role força logout de todos dispositivos do usuário</div>}
          </div>

          <div style={{padding:'10px 14px',background:active?'#F0FDF4':'#FEF2F2',border:'1px solid '+(active?'#16A34A44':'#DC262644'),borderRadius:8}}>
            <label style={{display:'flex',alignItems:'center',gap:10,cursor:isSelf?'not-allowed':'pointer'}}>
              <input
                type="checkbox"
                checked={active}
                onChange={e=>setActive(e.target.checked)}
                disabled={loading||isSelf}
                style={{width:18,height:18,cursor:isSelf?'not-allowed':'pointer'}}
              />
              <div>
                <div style={{fontSize:13,fontWeight:600,color:active?'#166534':'#991B1B'}}>
                  {active?'✅ Conta ativa':'🚫 Conta desativada'}
                </div>
                <div style={{fontSize:11,color:'#6B7280',marginTop:2}}>
                  {active
                    ?'Pode logar e acessar o sistema normalmente.'
                    :'⚠️ Não conseguirá logar. Sessions ativas serão invalidadas.'}
                </div>
              </div>
            </label>
            {isSelf && <div style={{fontSize:10,color:'#EA580C',marginTop:6}}>⚠️ Você não pode desativar a própria conta</div>}
          </div>

          <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:6}}>
            <button onClick={onClose} disabled={loading} style={{padding:'10px 20px',background:'#FFFFFF',color:'#374151',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14,fontWeight:600,cursor:loading?'not-allowed':'pointer'}}>
              Cancelar
            </button>
            <button onClick={handleSave} disabled={loading||!hasChanges||!name.trim()} style={{padding:'10px 20px',background:loading?'#9CA3AF':'#2563EB',color:'#FFFFFF',border:'none',borderRadius:6,fontSize:14,fontWeight:700,cursor:loading?'not-allowed':'pointer',opacity:!hasChanges?0.5:1}}>
              {loading?'⏳ Salvando...':'💾 Salvar'}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.EditUserModal = EditUserModal;
  window.EditUserModal = EditUserModal;
})();
