photum/frontend/pages/Register.tsx
NANDO9322 cf0cf4e95f feat(client): integra autenticacao real e melhora fluxo de login
- Integra AuthContext com API do Backend (/auth/login e /auth/register)
- Implementa Modo Hibrido: Demo Users usam Mock, outros usam API Real
- Habilita campo de senha e adiciona toggle de visibilidade (olho)
- Conecta formulario de Registro ao backend
- Adiciona preenchimento automatico de senha para usuarios de demonstracao
- Mapeia status 'ativo' do usuario vindo da API
2025-12-10 19:00:49 -03:00

316 lines
14 KiB
TypeScript

import React, { useState } from 'react';
import { Button } from '../components/Button';
import { Input } from '../components/Input';
import { InstitutionForm } from '../components/InstitutionForm';
import { useAuth } from '../contexts/AuthContext';
import { useData } from '../contexts/DataContext';
interface RegisterProps {
onNavigate: (page: string) => void;
}
export const Register: React.FC<RegisterProps> = ({ onNavigate }) => {
const { register } = useAuth();
const { addInstitution } = useData();
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
password: '',
confirmPassword: '',
wantsToAddInstitution: false
});
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const [isPending, setIsPending] = useState(false);
const [showInstitutionForm, setShowInstitutionForm] = useState(false);
const [tempUserId] = useState(`user-${Date.now()}`);
const [registeredInstitutionName, setRegisteredInstitutionName] = useState<string | undefined>();
const handleChange = (field: string, value: string | boolean) => {
setFormData(prev => ({ ...prev, [field]: value }));
setError('');
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setError('');
// Validação do checkbox de termos
if (!agreedToTerms) {
setError('Você precisa concordar com os termos de uso para continuar');
setIsLoading(false);
return;
}
// Validações
if (formData.password !== formData.confirmPassword) {
setError('As senhas não coincidem');
setIsLoading(false);
return;
}
if (formData.password.length < 6) {
setError('A senha deve ter no mínimo 6 caracteres');
setIsLoading(false);
return;
}
// If user wants to add institution, show form
if (formData.wantsToAddInstitution) {
setIsLoading(false);
setShowInstitutionForm(true);
return;
}
try {
await register({
nome: formData.name,
email: formData.email,
senha: formData.password,
telefone: formData.phone
});
setIsLoading(false);
setIsPending(true);
} catch (err: any) {
setIsLoading(false);
setError(err.message || 'Erro ao realizar cadastro');
}
};
const handleInstitutionSubmit = async (institutionData: any) => {
// Logic for adding institution remains (mock or need API for it too?),
// but user registration must be real.
// Assuming institution addition is still mock for now in DataContext.
const newInstitution = {
...institutionData,
id: `inst-${Date.now()}`,
ownerId: tempUserId
};
addInstitution(newInstitution);
setRegisteredInstitutionName(newInstitution.name);
setShowInstitutionForm(false);
// Complete registration via API
setIsLoading(true);
try {
await register({
nome: formData.name,
email: formData.email,
senha: formData.password,
telefone: formData.phone
// Note: The backend register endpoint currently doesn't accept institution data directly.
// We'd need to create the institution separately after logging in, but the user won't be able to login yet (pending).
// Or update backend to accept it.
// For now, we perform the user registration.
});
setIsLoading(false);
setIsPending(true);
} catch (err: any) {
setIsLoading(false);
setError(err.message || 'Erro ao realizar cadastro');
}
};
// Show institution form modal
if (showInstitutionForm) {
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<InstitutionForm
onCancel={() => {
// Apenas fecha o modal e volta para o formulário
setShowInstitutionForm(false);
// Desmarca a opção de cadastrar universidade
setFormData(prev => ({ ...prev, wantsToAddInstitution: false }));
}}
onSubmit={handleInstitutionSubmit}
userId={tempUserId}
/>
</div>
);
}
if (isPending) {
return (
<div className="min-h-screen flex items-center justify-center bg-white">
<div className="text-center fade-in max-w-md px-4">
<div className="w-16 h-16 bg-yellow-500 rounded-full flex items-center justify-center mx-auto mb-4">
<svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<h2 className="text-2xl font-bold text-gray-900 mb-2">Cadastro Pendente de Aprovação</h2>
<p className="text-gray-600 mb-4">
Seu cadastro foi realizado com sucesso e está aguardando aprovação da empresa.
</p>
<p className="text-gray-600 mb-6">
Você receberá um e-mail assim que seu cadastro for aprovado e poderá acessar o sistema.
</p>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
<p className="text-sm text-yellow-800">
<strong>Atenção:</strong> Enquanto seu cadastro não for aprovado, você não terá acesso ao sistema.
</p>
</div>
<button
onClick={() => {
setIsPending(false);
setFormData({
name: '',
email: '',
phone: '',
password: '',
confirmPassword: '',
wantsToAddInstitution: false
});
setAgreedToTerms(false);
}}
className="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
>
Fazer Novo Cadastro
</button>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-white p-4 py-8 pt-24">
<div className="w-full max-w-md fade-in relative z-10">
<div className="bg-white rounded-2xl shadow-xl border border-gray-100 p-6 sm:p-8">
{/* Logo dentro do card */}
<div className="flex justify-center mb-4">
<img
src="/logo.png"
alt="Photum Formaturas"
className="h-18 sm:h-30 w-auto max-w-[200px] object-contain"
/>
</div>
<div className="text-center">
<span className="font-bold tracking-widest uppercase text-xs sm:text-sm" style={{ color: '#B9CF33' }}>Comece agora</span>
<h2 className="mt-2 text-2xl sm:text-3xl font-serif font-bold text-gray-900">Crie sua conta</h2>
<p className="mt-2 text-xs sm:text-sm text-gray-600">
tem uma conta?{' '}
<button
onClick={() => onNavigate('entrar')}
className="font-medium hover:opacity-80 transition-opacity"
style={{ color: '#B9CF33' }}
>
Faça login
</button>
</p>
</div>
<form className="mt-6 space-y-4" onSubmit={handleSubmit}>
<div className="space-y-3">
<Input
label="Nome Completo"
type="text"
required
placeholder="João Silva"
value={formData.name}
onChange={(e) => handleChange('name', e.target.value)}
/>
<Input
label="E-mail"
type="email"
required
placeholder="nome@exemplo.com"
value={formData.email}
onChange={(e) => handleChange('email', e.target.value)}
/>
<Input
label="Telefone"
type="tel"
required
placeholder="(00) 00000-0000"
value={formData.phone}
onChange={(e) => handleChange('phone', e.target.value)}
mask="phone"
/>
<Input
label="Senha"
type="password"
required
placeholder="••••••••"
value={formData.password}
onChange={(e) => handleChange('password', e.target.value)}
/>
<Input
label="Confirmar Senha"
type="password"
required
placeholder="••••••••"
value={formData.confirmPassword}
onChange={(e) => handleChange('confirmPassword', e.target.value)}
error={error && (error.includes('senha') || error.includes('coincidem')) ? error : undefined}
/>
</div>
<div>
<div className="flex items-start">
<input
type="checkbox"
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
className="mt-0.5 sm:mt-1 h-4 w-4 flex-shrink-0 border-gray-300 rounded focus:ring-2"
style={{ accentColor: '#B9CF33' }}
/>
<label className="ml-2 text-xs sm:text-sm text-gray-600">
Concordo com os{' '}
<button
type="button"
onClick={() => onNavigate('termos')}
className="hover:opacity-80 transition-opacity underline"
style={{ color: '#B9CF33' }}
>
termos de uso
</button>{' '}
e{' '}
<button
type="button"
onClick={() => onNavigate('privacidade')}
className="hover:opacity-80 transition-opacity underline"
style={{ color: '#B9CF33' }}
>
política de privacidade
</button>
</label>
</div>
{error && error.includes('termos') && (
<span className="text-xs text-red-500 mt-1 block ml-6">{error}</span>
)}
</div>
<div className="flex items-start bg-gray-50 border border-gray-200 rounded-lg p-3 sm:p-4">
<input
type="checkbox"
checked={formData.wantsToAddInstitution}
onChange={(e) => setFormData(prev => ({ ...prev, wantsToAddInstitution: e.target.checked }))}
className="mt-0.5 sm:mt-1 h-4 w-4 flex-shrink-0 border-gray-300 rounded focus:ring-2"
style={{ accentColor: '#B9CF33' }}
/>
<label className="ml-2 text-xs sm:text-sm text-gray-700">
<span className="font-medium text-xs sm:text-sm">Cadastrar universidade agora (Opcional)</span>
<p className="text-[10px] sm:text-xs text-gray-500 mt-1">
Você pode cadastrar sua universidade durante o cadastro ou posteriormente no sistema.
Trabalhamos exclusivamente com eventos fotográficos em universidades.
</p>
</label>
</div>
<Button type="submit" className="w-full" size="lg" isLoading={isLoading}>
{formData.wantsToAddInstitution ? 'Continuar para Universidade' : 'Criar Conta'}
</Button>
</form>
</div>
</div>
</div>
);
};