// js/components/widgets/NewUserModal.jsx
// Admin cria novo usuario via RPC create_zaynex_user (cria auth.users + app_users + raw_app_meta_data role).
// Onda C+ V2 — 2026-05-06.
(function() {
  'use strict';
  const {useState} = React;

  function NewUserModal({onClose, onSuccess}){
    const[name,setName]=useState('');
    const[username,setUsername]=useState('');
    const[email,setEmail]=useState('');
    const[password,setPassword]=useState('');
    const[role,setRole]=useState('vendedor');
    const[loading,setLoading]=useState(false);
    const[showPwd,setShowPwd]=useState(false);

    // Auto-gera email a partir do username
    function handleUsernameChange(v){
      const clean = v.toLowerCase().replace(/[^a-z0-9._-]/g,'');
      setUsername(clean);
      if(!email || email.endsWith('@zaynex.local')){
        setEmail(clean + '@zaynex.local');
      }
    }

    async function handleCreate(){
      if(loading)return;
      if(!name.trim() || name.trim().length<2){toast('⚠️ Nome obrigatório','warning');return;}
      if(!username.trim() || username.trim().length<3){toast('⚠️ Username obrigatório (min 3 chars)','warning');return;}
      if(!email.trim() || !email.includes('@')){toast('⚠️ Email inválido','warning');return;}
      if(!password || password.length<6){toast('⚠️ Senha mín 6 caracteres','warning');return;}
      if(!['admin','vendedor','financeiro','estoquista'].includes(role)){toast('⚠️ Role inválido','warning');return;}

      setLoading(true);
      try {
        const{data,error}=await sb.rpc('create_zaynex_user',{
          p_email: email.trim().toLowerCase(),
          p_password: password,
          p_role: role,
          p_name: name.trim(),
          p_username: username.trim()
        });
        if(error){
          toast('❌ '+(error.message||'Erro ao criar usuário'),'error');
          if(typeof Sentry!=='undefined')Sentry.captureException(new Error(error.message),{extra:{context:'create_zaynex_user'}});
          return;
        }
        toast('✅ '+name+' criado como '+role+'. Senha temporária: '+password);
        if(typeof onSuccess==='function')onSuccess(data);
        onClose();
      } catch(e){
        toast('❌ Erro inesperado: '+(e?.message||'desconhecido'),'error');
      } finally {
        setLoading(false);
      }
    }

    return(
      <Modal title="➕ Novo usuário" onClose={onClose}>
        <div style={{display:'flex',flexDirection:'column',gap:14}}>
          <div style={{padding:'10px 14px',background:'#EEF2FF',border:'1px solid #6366F144',borderRadius:8,fontSize:12,color:'#3730A3'}}>
            💡 O usuário deve trocar a senha temporária no primeiro login (Meu Perfil → Trocar Senha).
          </div>

          <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="Ex: Maria Silva"
              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'}}>Username (login)</label>
            <input
              type="text"
              value={username}
              onChange={e=>handleUsernameChange(e.target.value)}
              placeholder="Ex: maria"
              style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14}}
              disabled={loading}
            />
            <div style={{fontSize:10,color:'#9CA3AF',marginTop:3}}>Apenas letras minúsculas, números, ponto, hífen e underscore.</div>
          </div>

          <div>
            <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>Email</label>
            <input
              type="email"
              value={email}
              onChange={e=>setEmail(e.target.value.toLowerCase())}
              placeholder="ex@zaynex.local"
              style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14}}
              disabled={loading}
            />
            <div style={{fontSize:10,color:'#9CA3AF',marginTop:3}}>Auto-preenchido com username@zaynex.local. Mude se quiser email pessoal real.</div>
          </div>

          <div>
            <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>Senha temporária (mín 6 chars)</label>
            <div style={{position:'relative'}}>
              <input
                type={showPwd?'text':'password'}
                value={password}
                onChange={e=>setPassword(e.target.value)}
                placeholder="Ex: zaynex1234"
                style={{width:'100%',padding:'10px 40px 10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14}}
                disabled={loading}
              />
              <button type="button" onClick={()=>setShowPwd(!showPwd)} style={{position:'absolute',right:8,top:'50%',transform:'translateY(-50%)',background:'transparent',border:'none',cursor:'pointer',fontSize:16,color:'#6B7280'}} tabIndex={-1}>
                {showPwd?'🙈':'👁️'}
              </button>
            </div>
            <button type="button" onClick={()=>setPassword('zaynex'+Math.floor(1000+Math.random()*9000))} style={{marginTop:4,fontSize:11,background:'transparent',border:'none',color:'#2563EB',cursor:'pointer',padding:0}}>🎲 Gerar senha aleatória</button>
          </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} style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14,background:'#FFFFFF'}}>
              <option value="vendedor">📞 Vendedor (cria orçamento, usa campanhas WhatsApp)</option>
              <option value="financeiro">💰 Financeiro (gerencia receber/pagar/comissão/credit)</option>
              <option value="estoquista">📦 Estoquista (recebe compras, devoluções, controla estoque)</option>
              <option value="admin">👑 Admin (acesso total — cuidado!)</option>
            </select>
          </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={handleCreate} disabled={loading||!name.trim()||!username.trim()||!password||password.length<6} style={{padding:'10px 20px',background:loading?'#9CA3AF':'#16A34A',color:'#FFFFFF',border:'none',borderRadius:6,fontSize:14,fontWeight:700,cursor:loading?'not-allowed':'pointer',opacity:(!name.trim()||!username.trim()||!password||password.length<6)?0.5:1}}>
              {loading?'⏳ Criando...':'➕ Criar usuário'}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

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