import { useState } from 'react'; import { useAuth } from '@/hooks/useAuth'; import { useNavigate } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { toast } from 'sonner'; import { Eye, EyeOff, Lock } from 'lucide-react'; export const PasswordResetForm = () => { const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); const { updatePassword } = useAuth(); const navigate = useNavigate(); // Password strength validation const validatePassword = (password: string) => { const minLength = password.length >= 8; const hasUpperCase = /[A-Z]/.test(password); const hasLowerCase = /[a-z]/.test(password); const hasNumbers = /\d/.test(password); const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password); const score = [minLength, hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChar].filter(Boolean).length; return { score, minLength, hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChar, isValid: score >= 4 && minLength }; }; const passwordStrength = validatePassword(password); const getPasswordStrengthColor = (score: number) => { if (score <= 2) return 'bg-red-500'; if (score <= 3) return 'bg-yellow-500'; return 'bg-green-500'; }; const getPasswordStrengthText = (score: number) => { if (score <= 2) return 'Fraca'; if (score <= 3) return 'Média'; return 'Forte'; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!password || !confirmPassword) { toast.error('Por favor, preencha todos os campos'); return; } if (!passwordStrength.isValid) { toast.error('A senha deve ter pelo menos 8 caracteres e incluir maiúsculas, minúsculas, números e símbolos'); return; } if (password !== confirmPassword) { toast.error('As senhas não coincidem'); return; } setIsLoading(true); try { console.log('🔄 Iniciando redefinição de senha...'); const { error } = await updatePassword(password); if (error) { console.error('❌ Erro ao redefinir senha:', error); // Tratamento específico de erros let errorMessage = 'Erro ao redefinir senha. Tente novamente.'; if (error.message?.includes('session_not_found')) { errorMessage = 'Sessão expirada. Solicite um novo link de redefinição.'; } else if (error.message?.includes('same_password')) { errorMessage = 'A nova senha deve ser diferente da anterior.'; } else if (error.message?.includes('password_invalid')) { errorMessage = 'Senha inválida. Verifique os critérios de segurança.'; } else if (error.message) { errorMessage = `Erro: ${error.message}`; } toast.error(errorMessage); } else { console.log('✅ Senha redefinida com sucesso!'); toast.success('Senha redefinida com sucesso! Redirecionando...'); // Aguardar um pouco antes de redirecionar para mostrar a mensagem setTimeout(() => { navigate('/'); }, 1500); } } catch (error) { console.error('❌ Erro inesperado:', error); toast.error('Erro inesperado ao redefinir senha. Tente novamente.'); } finally { setIsLoading(false); } }; return (
Redefinir Senha Digite sua nova senha abaixo
setPassword(e.target.value)} className="pl-10 pr-10 h-12" disabled={isLoading} />
{/* Password Strength Indicator */} {password && (
{getPasswordStrengthText(passwordStrength.score)}
Mínimo 8 caracteres
Letra maiúscula
Número
Símbolo especial
)}
setConfirmPassword(e.target.value)} className="pl-10 h-12" disabled={isLoading} />
); };