import {useState,useContext} from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {UserCtx, UserCtxT} from '../context/UserContext';
import './Login.css'

const Login = () => 
{
    const {loginUser, wait, getUser, user} = useContext<UserCtxT | null>(UserCtx) as UserCtxT;
    const [redirect, setRedirect] = useState("false");
    const [errMsg, setErrMsg] = useState("false");
    const [formData, setFormData] = useState({
        email:'',
        password:''
    });
    const navigate = useNavigate();

    const onChangeInput = (e: React.FormEvent<HTMLInputElement>) => 
    {
        if(e.currentTarget.type === 'email' || e.currentTarget.type === 'password')
        {
            setFormData({
                ...formData,
                [e.currentTarget.name]:e.currentTarget.value
            });
        }
    }

    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => 
    {
        e.preventDefault();

        if(!Object.values(formData).every(val => val.trim() !== ''))
        {
            setErrMsg('Please Fill in all Required Fields!');
            return;
        }

        const data = await loginUser(formData);
        if(data.success)
        {
            setRedirect('Redirecting...');
            setErrMsg(data.message);
            await getUser();
            navigate('/profil');
            return;
        }
        setErrMsg(data.message);
    }

    return (
        <div className='Login'>
            <h2>Login</h2>
            { user &&
            <>
            <div>Logged in als:</div>
            <div>{user?.email}</div>
            <div className="bottom-link"><Link to="/">Home</Link></div> 
            </> }

            {!user &&<form onSubmit={submitForm}>
                <div>
                    <label htmlFor="email">Email:</label>
                    <input type="email" name="email" onChange={onChangeInput} placeholder="Your email" id="email" value={formData.email} required />
                </div>
                <div>
                    <label htmlFor="password">Password:</label>
                    <input type="password" name="password" onChange={onChangeInput} placeholder="New password" id="password" value={formData.password} required />
                </div>
                {errMsg !== "false" && <div className="err-msg">{errMsg}</div>}
                {redirect  !== "false" ? redirect : <button type="submit" disabled={wait}>Login</button>}
                <div className="bottom-link"><Link to="/reg">Register</Link></div>
            </form> }
        </div>
    )
}
export default Login;