import {useState,useContext} from 'react';
import { Link } from 'react-router-dom';
import {UserCtx, UserCtxT} from '../context/UserContext';
const Login = () => {
    const {loginUser, wait, getUser} = useContext<UserCtxT | null>(UserCtx) as UserCtxT;
    const [redirect, setRedirect] = useState("false");
    const [errMsg, setErrMsg] = useState("false");
    const [formData, setFormData] = useState({
        email:'',
        password:''
    });

    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...');
            await getUser();
            //e.currentTarget.reset();
            return;
        }
        setErrMsg(data.message);
    }

    return (
        <div>
            <h2>Login</h2>
            <form onSubmit={submitForm}>
                <label htmlFor="email">Email:</label>
                <input type="email" name="email" onChange={onChangeInput} placeholder="Your email" id="email" value={formData.email} required />
                <label htmlFor="password">Password:</label>
                <input type="password" name="password" onChange={onChangeInput} placeholder="New password" id="password" value={formData.password} required />
                {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;