import React, { useState } from 'react';
import './SignUp.css';
import { useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';

function SignUp() {
    console.log('SignUp component rendered!');

    const [username, setUsername] = useState('');
    const [fullName, setFullName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [securityQuestion, setSecurityQuestion] = useState('');
    const [securityAnswer, setSecurityAnswer] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate(); // For navigation

    const handleSignUp = async (e) => {
        e.preventDefault(); // Prevent default form submission
    
        if (password !== confirmPassword) {
            setError("Passwords don't match!");
            return;
        }
    
        try {
            const response = await fetch('http://127.0.0.1:5001/register', { // Update with your API endpoint
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username,
                    fullName,
                    email,
                    password,
                    securityQuestion,
                    securityAnswer
                }),
            });
    
            const result = await response.json();
            console.log(result); // Log the result for debugging
    
            if (result.success) {
                console.log('Registration successful');
                navigate('/'); // Redirect to login page after successful registration
            } else {
                setError(result.message); // Show error message from backend
            }
        } catch (error) {
            console.error('Error:', error); // Log the error for debugging
            setError(error.message);
        }
    };
  
    // Return a JSX element that represents the sign-up page
    return (
        <div className="container">
            <div className="title">
                <h1>Sign Up</h1>
            </div>

            <div className="join">
                <p> We would love to have you join our sniffer community! Sign-up below to begin.</p>
            </div>

            <form className="form" onSubmit={handleSignUp}>
                <input 
                    type="text" 
                    value={fullName} 
                    onChange={(e) => setFullName(e.target.value)} 
                    placeholder="Full Name" 
                    required 
                />
                <input 
                    type="text" 
                    value={username} 
                    onChange={(e) => setUsername(e.target.value)} 
                    placeholder="Username" 
                    required 
                />
                <input 
                    type="email" 
                    value={email} 
                    onChange={(e) => setEmail(e.target.value)} 
                    placeholder="Email" 
                    required 
                />
                <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 
                />
                <select 
                    value={securityQuestion} 
                    onChange={(e) => setSecurityQuestion(e.target.value)} 
                    required
                >
                    <option value="" disabled>Select a security question</option>
                    <option value="What is your mother's maiden name?">What is your mother's maiden name?</option>
                    <option value="What was the name of your first pet?">What was the name of your first pet?</option>
                    <option value="What was the name of your elementary school?">What was the name of your elementary school?</option>
                </select>
                <input 
                    type="text" 
                    value={securityAnswer} 
                    onChange={(e) => setSecurityAnswer(e.target.value)} 
                    placeholder="Answer to security question" 
                    required 
                />
                <button className="signup-button" type="submit">Sign Up</button>

                {error && <div className="error">{error}</div>} {/* Display error message */}
            </form>
            <p>By clicking the "Sign Up" button, you are creating an account, and you agree to the Terms of Use.</p>
                <div className="back">
                <p>
                    <Link to="/">Back to Sign In</Link>
                </p>
                </div>
        </div>
    );
}

export default SignUp;