
// Usuarios Module

function Usuarios() {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showModal, setShowModal] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', email: '', password: '', role: 'usuario', department: '' });
  const [creating, setCreating] = React.useState(false);
  const [showPass, setShowPass] = React.useState(false);
  const [editTarget, setEditTarget] = React.useState(null);
  const [editForm, setEditForm] = React.useState({ name: '', role: 'usuario', department: '' });
  const [editSaving, setEditSaving] = React.useState(false);
  const [resetTarget, setResetTarget] = React.useState(null);
  const [resetForm, setResetForm] = React.useState({ password: '', show: false });
  const [resetSaving, setResetSaving] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3500); };

  const fetchUsers = () => {
    sb.from('app_users').select('*').order('created_at', { ascending: false }).then(({ data }) => {
      setUsers(data || []);
      setLoading(false);
    });
  };

  React.useEffect(() => { fetchUsers(); }, []);

  const handleCreate = async () => {
    if (!form.email.trim() || !form.password.trim()) {
      showToast('Preencha e-mail e senha.', 'error'); return;
    }
    if (form.password.length < 6) {
      showToast('Senha precisa ter pelo menos 6 caracteres.', 'error'); return;
    }
    setCreating(true);

    const tempClient = supabase.createClient(window.SUPA_URL, window.SUPA_KEY, {
      auth: { persistSession: false, autoRefreshToken: false },
    });

    const { data: authData, error: authErr } = await tempClient.auth.signUp({
      email: form.email.trim().toLowerCase(),
      password: form.password,
    });

    if (authErr) {
      const msg = authErr.message.includes('already') ? 'E-mail já cadastrado.' : 'Erro ao criar usuário: ' + authErr.message;
      showToast(msg, 'error');
      setCreating(false);
      return;
    }

    // Upsert porque o trigger handle_new_auth_user pode ter inserido a linha
    // primeiro (com role default 'usuario' e department NULL) — aqui sobrescrevemos
    // com os valores que o admin escolheu na tela.
    await sb.from('app_users').upsert({
      id: authData.user?.id,
      email: form.email.trim().toLowerCase(),
      name: form.name.trim() || form.email.split('@')[0],
      role: form.role,
      department: form.department || null,
    }, { onConflict: 'id' });

    showToast('Usuário criado com sucesso!');
    setForm({ name: '', email: '', password: '', role: 'usuario', department: '' });
    setShowModal(false);
    fetchUsers();
    setCreating(false);
  };

  const openEdit = (user) => {
    setEditTarget(user);
    setEditForm({ name: user.name || '', role: user.role || 'usuario', department: user.department || '' });
  };

  const handleEditSave = async () => {
    if (!editTarget) return;
    setEditSaving(true);
    const { error } = await sb.from('app_users').update({
      name: editForm.name.trim() || editTarget.email.split('@')[0],
      role: editForm.role,
      department: editForm.department || null,
    }).eq('id', editTarget.id);
    setEditSaving(false);
    if (error) {
      showToast('Erro ao salvar: ' + (error.message || 'tente novamente.'), 'error');
      return;
    }
    showToast('Usuário atualizado!');
    setEditTarget(null);
    fetchUsers();
  };

  const openReset = (user) => {
    setResetTarget(user);
    setResetForm({ password: '', show: false });
  };

  const handleSetPassword = async () => {
    if (!resetTarget) return;
    if (resetForm.password.length < 6) {
      showToast('Senha precisa ter pelo menos 6 caracteres.', 'error');
      return;
    }
    setResetSaving(true);
    const { error } = await sb.rpc('admin_set_user_password', {
      p_user_id: resetTarget.id,
      p_new_password: resetForm.password,
    });
    setResetSaving(false);
    if (error) {
      showToast('Erro ao redefinir senha: ' + (error.message || 'tente novamente.'), 'error');
      return;
    }
    showToast(`Senha de ${resetTarget.name || resetTarget.email} redefinida!`);
    setResetTarget(null);
    setResetForm({ password: '', show: false });
  };

  const handleDelete = async (user) => {
    if (!window.confirm(`Remover ${user.name || user.email} do sistema?`)) return;
    await sb.from('app_users').delete().eq('id', user.id);
    showToast('Usuário removido da lista.');
    fetchUsers();
  };

  const roleLabel = { admin: 'Administrador', usuario: 'Usuário', visualizador: 'Visualizador' };
  const roleColor = { admin: 'danger', usuario: 'primary', visualizador: 'default' };

  const fmtDate = (iso) => iso ? new Date(iso).toLocaleDateString('pt-BR') : '—';

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '10px 13px', fontSize: 13, border: `1.5px solid ${DS.colors.border}`,
    borderRadius: DS.radius.sm, outline: 'none', fontFamily: 'Inter, sans-serif',
    color: DS.colors.text, background: '#F8FAFC',
  };

  if (loading) {
    return (
      <div>
        <div style={{ marginBottom: 28 }}>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0 }}>Usuários</h1>
        </div>
        <Spinner />
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Usuários</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Gerencie quem tem acesso ao sistema</p>
        </div>
        <Btn icon="plus" onClick={() => setShowModal(true)}>Novo usuário</Btn>
      </div>

      <Card>
        {users.length === 0 ? (
          <div style={{ padding: '48px 24px', textAlign: 'center', color: DS.colors.textMuted }}>
            <Icon name="users" size={36} color={DS.colors.border} />
            <div style={{ fontSize: 14, fontWeight: 600, color: DS.colors.textSec, marginTop: 12 }}>Nenhum usuário cadastrado</div>
            <div style={{ fontSize: 13, marginTop: 4 }}>Clique em "Novo usuário" para adicionar alguém.</div>
          </div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 2fr 0.9fr 1fr 0.9fr 1.2fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              <span>Nome</span><span>E-mail</span><span>Perfil</span><span>Setor</span><span>Criado em</span><span style={{ textAlign: 'right' }}>Ações</span>
            </div>
            {users.map((u, i) => (
              <div key={u.id} style={{ display: 'grid', gridTemplateColumns: '1.6fr 2fr 0.9fr 1fr 0.9fr 1.2fr', padding: '14px 24px', borderBottom: i < users.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Avatar name={u.name || u.email} size={32} color={DS.colors.primary} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{u.name || '—'}</span>
                </div>
                <span style={{ fontSize: 13, color: DS.colors.textSec, overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.email}</span>
                <span><Badge variant={roleColor[u.role] || 'default'}>{roleLabel[u.role] || u.role}</Badge></span>
                <span style={{ fontSize: 13, color: u.department ? DS.colors.text : DS.colors.textMuted, fontWeight: u.department ? 600 : 400 }}>{deptLabel(u.department)}</span>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{fmtDate(u.created_at)}</span>
                <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                  <Btn variant="ghost" size="sm" onClick={() => openEdit(u)}>Editar</Btn>
                  <Btn variant="ghost" size="sm" onClick={() => openReset(u)}>Senha</Btn>
                  <button onClick={() => handleDelete(u)}
                    style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: '4px 6px', borderRadius: DS.radius.sm, color: DS.colors.textMuted }}
                    onMouseEnter={e => e.currentTarget.style.color = '#EF4444'}
                    onMouseLeave={e => e.currentTarget.style.color = DS.colors.textMuted}>
                    <Icon name="trash" size={14} color="currentColor" />
                  </button>
                </div>
              </div>
            ))}
          </>
        )}
      </Card>

      {showModal && (
        <Modal open={showModal} onClose={() => { setShowModal(false); setForm({ name: '', email: '', password: '', role: 'usuario', department: '' }); }} title="Novo usuário" width={480}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Nome completo</label>
              <input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Ex: João Silva" style={inputStyle} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>E-mail *</label>
              <input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} placeholder="usuario@email.com" style={inputStyle} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Senha *</label>
              <div style={{ position: 'relative' }}>
                <input type={showPass ? 'text' : 'password'} value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} placeholder="Mínimo 6 caracteres" style={{ ...inputStyle, paddingRight: 44 }} />
                <button onClick={() => setShowPass(s => !s)} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', border: 'none', background: 'transparent', cursor: 'pointer', padding: 4 }}>
                  <Icon name="eye" size={15} color={showPass ? DS.colors.primary : DS.colors.textMuted} />
                </button>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Perfil de acesso</label>
                <select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))} style={{ ...inputStyle }}>
                  <option value="admin">Administrador</option>
                  <option value="usuario">Usuário</option>
                  <option value="visualizador">Visualizador</option>
                </select>
              </div>
              <div>
                <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Setor *</label>
                <select value={form.department} onChange={e => setForm(f => ({ ...f, department: e.target.value }))} style={{ ...inputStyle }}>
                  {DEPT_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </div>
            </div>
            <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: -8 }}>
              <strong>Admin / Financeiro</strong> veem todos os módulos e valores. Demais setores não veem o módulo Financeiro nem valores em R$.
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 8 }}>
              <Btn variant="secondary" onClick={() => { setShowModal(false); setForm({ name: '', email: '', password: '', role: 'usuario', department: '' }); }}>Cancelar</Btn>
              <Btn onClick={handleCreate} disabled={creating}>
                {creating ? 'Criando…' : 'Criar usuário'}
              </Btn>
            </div>
          </div>
        </Modal>
      )}

      {editTarget && (
        <Modal open={!!editTarget} onClose={() => setEditTarget(null)} title="Editar usuário" width={460}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ padding: 12, background: '#F8FAFC', borderRadius: DS.radius.sm, borderLeft: `3px solid ${DS.colors.primary}` }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Editando</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{editTarget.email}</div>
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Nome completo</label>
              <input value={editForm.name} onChange={e => setEditForm(f => ({ ...f, name: e.target.value }))} style={inputStyle} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Perfil de acesso</label>
                <select value={editForm.role} onChange={e => setEditForm(f => ({ ...f, role: e.target.value }))} style={inputStyle}>
                  <option value="admin">Administrador</option>
                  <option value="usuario">Usuário</option>
                  <option value="visualizador">Visualizador</option>
                </select>
              </div>
              <div>
                <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Setor *</label>
                <select value={editForm.department} onChange={e => setEditForm(f => ({ ...f, department: e.target.value }))} style={inputStyle}>
                  {DEPT_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 4 }}>
              <Btn variant="secondary" onClick={() => setEditTarget(null)}>Cancelar</Btn>
              <Btn onClick={handleEditSave} disabled={editSaving}>{editSaving ? 'Salvando…' : 'Salvar'}</Btn>
            </div>
          </div>
        </Modal>
      )}

      {resetTarget && (
        <Modal open={!!resetTarget} onClose={() => { setResetTarget(null); setResetForm({ password: '', show: false }); }} title="Definir nova senha" width={440}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ padding: 12, background: '#F8FAFC', borderRadius: DS.radius.sm, borderLeft: `3px solid ${DS.colors.primary}` }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Usuário</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{resetTarget.name || resetTarget.email}</div>
              <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 2 }}>{resetTarget.email}</div>
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: DS.colors.textSec, display: 'block', marginBottom: 6 }}>Nova senha *</label>
              <div style={{ position: 'relative' }}>
                <input
                  type={resetForm.show ? 'text' : 'password'}
                  value={resetForm.password}
                  onChange={e => setResetForm(f => ({ ...f, password: e.target.value }))}
                  placeholder="Mínimo 6 caracteres"
                  style={{ ...inputStyle, paddingRight: 44 }}
                  autoFocus
                />
                <button onClick={() => setResetForm(f => ({ ...f, show: !f.show }))}
                  style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', border: 'none', background: 'transparent', cursor: 'pointer', padding: 4 }}>
                  <Icon name="eye" size={15} color={resetForm.show ? DS.colors.primary : DS.colors.textMuted} />
                </button>
              </div>
              <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 6 }}>
                A senha atual será substituída. Informe a nova senha ao usuário pessoalmente.
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 4 }}>
              <Btn variant="secondary" onClick={() => { setResetTarget(null); setResetForm({ password: '', show: false }); }}>Cancelar</Btn>
              <Btn onClick={handleSetPassword} disabled={resetSaving}>
                {resetSaving ? 'Salvando…' : 'Definir senha'}
              </Btn>
            </div>
          </div>
        </Modal>
      )}

      {toast && <Toast message={toast.msg} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Usuarios });
