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';
//import { eNotif, useNotificationStore } from "../services/NotificationStore";

 
const Login = () => 
{
    const [formData, setFormData] = useState({
            email:'',
        password:''
    });
    // only for redirect
    const {data, error, isLoading, mutate} = useSWR("/login", getUser);
//    const { AddNotification, DeleteNotification, queue } = useNotificationStore(); 
    //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)
    {
//        AddNotification({type: eNotif.success, msg: 'Login erfolgreich!'});
        window.location.href = '/dog/';
    }

    // if(queue.length > 0)
    // {
    //     console.log('queue');    
    //     console.log(queue);
    //     const not = queue[queue.length-1];

    //     switch (not.type) {
    //         case eNotif.success:
    //             notificationSuccess(not.msg);
    //             break;
    //         case eNotif.error:
    //             notificationError(not.msg);
    //             break;
    //         case eNotif.alert:
    //         default:
    //             notificationAlert(not.msg);        
    //     }
    //     DeleteNotification();
    // }

  
    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;