import React, {useState} from 'react';
import './ForgotPwd.css';
import { BrowserRouter as Router, Route, Routes, useNavigate, Link } from 'react-router-dom';
import SignIn from './App';     // To go back to the sign in page
import SignUp from './SignUp';  // To go back to the sign up page

function ForgotPassword() {
    const [username, setUsername] = useState('');
    const [securityQuestion, setSecurityQuestion] = useState('');
    const [securityAnswer, setSecurityAnswer] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate();
    const [step, setStep] = useState(1); // Step 1: Enter username, Step 2: Answer security question

    const handleRetrieveSecurityQuestion = async () => {
        try {
            const response = await fetch('http://127.0.0.1:5001/retrieve_security_question', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username }),
            });

            const result = await response.json();

            if (result.success) {
                setSecurityQuestion(result.securityQuestion);
                setError('');
                setStep(2); // Move to step 2
            } else {
                setError(result.message);
                setSecurityQuestion('');
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
            setSecurityQuestion('');
        }
    };

  const handleVerifySecurityAnswer = async () => {
        try {
            const response = await fetch('http://127.0.0.1:5001/verify_security_answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, securityAnswer }),
            });

            const result = await response.json();

            if (result.success) {
                // Handle successful verification (e.g., redirect to reset password page)
                console.log('Security answer verified');
                // Redirect to reset password page or show a success message
                setStep(3); // Move to step 3
            } else {
                setError(result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
    };

    const handleResetPassword = async () => {
        try {
            const response = await fetch('http://127.0.0.1:5001/reset_password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ password, confirmPassword, username }), 
            });

            const result = await response.json();

            if (result.success) {
                // Handle successful verification (e.g., redirect to reset password page)
                console.log('Security answer verified');
                // Redirect to reset password page or show a success message
                navigate("/")
            } else {
                setError(result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
    };

    return (
        <div className="container">
            <div className="title">
                <h1>Forgot Password</h1>
            </div>

            {step === 1 && (
                <>
                    <div className="note">
                        <p> </p>
                    </div>

                    <div className="form">
                        <label htmlFor="username">Username</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            placeholder="Enter your username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </div>

                    <div className="reset-button">
                        <button onClick={handleRetrieveSecurityQuestion}>Retrieve Security Question</button>
                    </div>
                </>
            )}

            {step === 2 && (
                <>
                    <div className="security-question">
                        <p>{securityQuestion}</p>
                    </div>

                    <div className="form">
                        <label htmlFor="securityAnswer">Answer</label>
                        <input
                            type="text"
                            id="securityAnswer"
                            name="securityAnswer"
                            placeholder="Enter your answer"
                            value={securityAnswer}
                            onChange={(e) => setSecurityAnswer(e.target.value)}
                        />
                    </div>

                    <div className="reset-button">
                        <button onClick={handleVerifySecurityAnswer}>Submit Answer</button>
                    </div>
                </>
            )}

            {step === 3 && (
                <>
                    <div className="password">
                        <p>{"Enter new password"}</p>
                    </div>

                    <div className="form">
                    <input 
                    type="password" 
                    value={password} 
                    onChange={(e) => setPassword(e.target.value)} 
                    placeholder="Password" 
                    required 
                />
                    <input 
                    type="password" 
                    value={confirmPassword} 
                    onChange={(e) => setConfirmPassword(e.target.value)} 
                    placeholder="Confirm Password" 
                    required 
                />
                    </div>

                    <div className="reset-button">
                        <button onClick={handleResetPassword}>Reset password</button>
                    </div>
                </>
            )}

            <div className="error-messages">
                {error && <p>{error}</p>}
            </div>

            <div className="back">
                <p>
                    <Link to="/">Back to Sign In</Link>
                </p>
            </div>
        </div>
    );
}

export default ForgotPassword;