import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './Settings.css';
import { useAuth } from './authentication_context';

const Settings = () => {
    const navigate = useNavigate();
    const usercredentials = JSON.parse(localStorage.getItem('user'));
    const rememberMe = usercredentials.rememberMe;
    const [cur_email, setcur_email] = useState(''); // State for security question
    const [cur_securityQuestion, setcur_securityQuestion] = useState(''); // State for security question
    const [error, setError] = useState('');
    const { login } = useAuth();

    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        securityQuestion: '',
        securityAnswer: '',
    });
    
    const [initialFormData, setInitialFormData] = useState({
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        securityQuestion: '',
        securityAnswer: '',
    });

    useEffect(() => {
        getEmailAndSecurityQuestion();
    }, []); // Run only once on mount


    const goBack = () => {
        navigate('/dashboard');
    }

    const getEmailAndSecurityQuestion = 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:usercredentials.username} )),
            });

            const result = await response.json();

            if (result.success) {
                console.log("Fetched security question successfully");
                console.log(result.securityQuestion);
                setFormData((prevFormData) => ({ 
                    ...prevFormData, 
                    securityQuestion: result.securityQuestion, }));
                setInitialFormData((prevFormData) => ({ 
                    ...prevFormData, 
                    securityQuestion: result.securityQuestion, }));
            } else {
                setError(result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
        try {
            const response = await fetch('http://127.0.0.1:5001/retrieve_email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify( {username:usercredentials.username} ),
            });

            const result = await response.json();

            if (result.success) {
                console.log("Fetched email successfully");
                setcur_email(result.email); // Update state with fetched question
            } else {
                setError(result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
    };

    const updateUserSettings = async (changes) => {
        try {
            console.log(changes);
            const response = await fetch('http://127.0.0.1:5001/update_user_settings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(changes),
            });
        
            const result = await response.json();
            if (result.success) {
                setFormData((prevFormData) => ({
                ...prevFormData,
                ...changes,
                }));
            const new_credentials = {}
            if (changes.username) {
                new_credentials.username = changes.username;
            }
            else {
                new_credentials.username = usercredentials.username;
            }
            if (changes.password) {
                new_credentials.password = changes.password;
            }
            else {
                new_credentials.password = usercredentials.password;
            }
            new_credentials.rememberMe = rememberMe;
            if (changes.username || changes.password) {
                localStorage.setItem('user', JSON.stringify(new_credentials));
            }
            
            } else {
            setError(result.message);
            }
        } catch (error) {
            console.error('Error updating user settings:', error);
            setError('An error occurred while updating user settings.');
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const old_password = prompt("Enter your current password to apply updates:");
        if (!old_password) {
            alert("Password is required!");
            return;
        }
        
        const credentials = {
            username: usercredentials.username,
            password: old_password,
        };
        
        try {
            await login(credentials, rememberMe);
        } catch (err) {
            setError('Incorrect password. Please try again.');
            return;
        }
        
        const changes = {};
        changes.old_username = usercredentials.username;

        if (formData.email !== initialFormData.email) {
            changes.email = formData.email;
        }
        if (formData.securityQuestion !== initialFormData.securityQuestion) {
            changes.securityQuestion = formData.securityQuestion;
            console.log("security question changed");
        }
        if (formData.securityAnswer !== initialFormData.securityAnswer) {
            changes.securityAnswer = formData.securityAnswer;
        }
        if (formData.username !== initialFormData.username) {
            changes.username = formData.username;
        }

        if (formData.password !== initialFormData.password) {
            changes.password = formData.password;
        }

        if (formData.confirmPassword !== initialFormData.confirmPassword) {
            changes.confirmpassword = formData.confirmPassword;
        }
        
        if (Object.keys(changes).length > 0) {
            await updateUserSettings(changes);
        } else {
            console.log('No changes to update.');
        }

    };

    return (
        <div className="settings-container">
            <h1>Settings</h1>
            <form onSubmit={handleSubmit} className="settings-form">
                <label>
                    Username:
                </label>
                <input
                    type="text"
                    name="username"
                    value={formData.username}
                    placeholder = {usercredentials.username}
                    onChange={handleChange}
                />

                <label>
                    Email:
                </label>
                <input
                    type="email"
                    name="email"
                    value={formData.email}
                    placeholder = {cur_email}
                    onChange={handleChange}
                />

                <label>
                    Password:
                </label>
                <input
                    type="password"
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                />

                <label>
                    Confirm Password:
                </label>
                <input
                    type="password" 
                    name="confirmPassword"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                />

                <label>
                    Security Question:
                </label>
                <select 
                    name="securityQuestion"
                    value={formData.securityQuestion} 
                    onChange={handleChange}
                >
                    <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>

                <label>
                    Security Answer:
                </label>
                <input 
                    type="password" 
                    name="securityAnswer"
                    value={formData.securityAnswer} 
                    onChange={handleChange}
                    placeholder="Answer to security question"  
                />

                <button type="submit">Update Settings</button>
                <button type="button" onClick={goBack}>Back to Dashboard</button>
            </form>

            {error && <div className="error">{error}</div>}
        </div>
    );
};

export default Settings;