import {useState} from 'react';
import { Link/*, useNavigate*/ } from 'react-router-dom';
import './Login.css';
import {getUser, loginUser} from '../services/PhpApi'
import { toast, Toaster } from 'react-hot-toast';
import useSWR from 'swr';

const Login = () => 
{
    const [formData, setFormData] = useState({
            email:'',
        password:''
    });
    // only for redirect
    const {data, error, isLoading, mutate} = useSWR("/login", getUser);
    //const navigate = useNavigate();
    console.log('Login getUser');
    console.log(data);

    if (error)
    { 
      toast.error(error.message);
      return (
        <>
          <Toaster toastOptions={{ position: "top-center" }} />
          <div>failed to load</div>
        </>);
    }
    if (isLoading) return (<div>loading...</div>);

    if(data.success)
    {
        window.location.href = '/dog/';
    }
  
    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() !== ''))
        {
            toast.error('Please Fill in all Required Fields!');
            return;
        }

        const logResp = await loginUser(formData);
        if(logResp.success)
        {
            toast.success(logResp.message);
            mutate(); // update swr
        }
        else
        {
            toast.error(logResp.message);
        }
    }

    return (
        <div className='Login'>
            <Toaster toastOptions={{ position: "top-center" }} />
            <h2>Login</h2>

            <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>
                <button type="submit">Login</button>
                <div className="bottom-link"><Link to="/reg">Register</Link></div>
            </form>
        </div>
    )
}
export default Login;