import React, { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { supabase } from '../lib/supabase'; import { KeyRound, Lock, AlertCircle } from 'lucide-react'; export function UpdatePassword() { const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const navigate = useNavigate(); const location = useLocation(); useEffect(() => { // Check for error parameters in the URL hash const hashParams = new URLSearchParams(location.hash.replace('#', '')); const errorCode = hashParams.get('error_code'); const errorDescription = hashParams.get('error_description'); if (errorCode === 'otp_expired') { setError('Your password reset link has expired. Redirecting to request a new one...'); setTimeout(() => { navigate('/reset-password', { replace: true }); }, 3000); return; } // Check if we have a valid session const checkSession = async () => { const { data: { session } } = await supabase.auth.getSession(); if (!session) { setError('Invalid or expired password reset link. Please request a new one.'); setTimeout(() => { navigate('/reset-password', { replace: true }); }, 3000); } }; checkSession(); }, [navigate, location.hash]); const handleUpdatePassword = async (e: React.FormEvent) => { e.preventDefault(); setError(''); setLoading(true); if (password.length < 6) { setError('Password must be at least 6 characters long'); setLoading(false); return; } if (password !== confirmPassword) { setError('Passwords do not match'); setLoading(false); return; } try { const { error } = await supabase.auth.updateUser({ password: password }); if (error) throw error; // Show success message before redirecting const successMessage = document.createElement('div'); successMessage.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-md shadow-lg z-50'; successMessage.textContent = 'Password updated successfully!'; document.body.appendChild(successMessage); // Remove the message after 3 seconds setTimeout(() => { document.body.removeChild(successMessage); navigate('/login', { replace: true }); }, 3000); } catch (error: any) { if (error.message.includes('auth')) { setError('Your password reset link has expired. Please request a new one.'); setTimeout(() => { navigate('/reset-password', { replace: true }); }, 3000); } else { setError(error.message); } } finally { setLoading(false); } }; return (
Enter your new password