import {useState} from 'react';
import { Link/*, useNavigate*/ } from 'react-router-dom';
import './InputForm.css';
import {getUser, loginUser} from '../services/PhpApi'
import useSWR from 'swr';
import { PasswordInput, Stack, TextInput } from '@mantine/core';
import { notificationAlert, notificationError, notificationSuccess } from '../services/Notifications';


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)
    { 
      notificationError(error.message);

      return (
        <>
          <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' || e.currentTarget.type === 'text')
        {
            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() !== ''))
        {
            notificationAlert('Bitte alle Felder ausfüllen!');
            return;
        }

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

    return (
        <div className='InputForm'>
            <h2>Login</h2>
            <div className='frameCenter'>
            <div className='frame'>
            <form onSubmit={submitForm}>
                <Stack align="flex-start" sx={{textAlign: 'left'}}>
                <TextInput
                    label = 'Email:'
                    type="email" 
                    name="email" 
                    onChange={onChangeInput} 
                    placeholder="Deine Email" 
                    id="email" 
                    value={formData.email} 
                    required />
                <PasswordInput className='IF_pw'
                    sx = {{  maxWidth: '80vw', minWidth: '30vw', width: '300px' }}
                    label = 'Passwort:'
                    name="password" 
                    onChange={onChangeInput} 
                    placeholder="New password" 
                    id="password" value={formData.password} 
                    required/>
                </Stack>
                <button type="submit">Login</button>
                <div className="bottom-link"><Link to="/reg">Register</Link></div>
                <div className="bottom-link"><Link to="/wantnewpw">Passwort vergessen</Link></div>
            </form>
            </div>
            </div>
        </div>
    )
}
export default Login;