import React from 'react';
import { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import '../styles/type.css';

import { useWindowDimensions } from '../components/UseWindowDimensions'

import { Input } from '../components/Input';
import { Button } from '../components/Button';
import { Message } from '../components/Message';

export const LoginForm = () => {

    // Form data.
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    // Errors.
    const [emailError, setEmailError] = useState('');
    const [passwordError, setPasswordError] = useState('');

    // Loading.
    const [loading, setLoading] = useState(false);

    // Window.
    const { width } = useWindowDimensions()

    // Submit form. 
    const submit = () => {
        // Do a fetch here normally.
        setLoading(true);
       
        setTimeout(function() {

            // Set errors.
            if(email.length < 1){
                setEmailError('Email required')
            } else {
                setEmailError('')
            }
        
            if(password.length < 1){
                setPasswordError('Password required')
            } else {
                setPasswordError('')
            }

            setLoading(false);

        }, 2000);
        
    }

    return (
        <>
            <div style={{ maxWidth: 400, marginLeft: 'auto', marginRight: 'auto', paddingTop: 36 }} >
                
                <h3 style={{marginBottom: 24}}>Login</h3>
                
                <label style={{ marginLeft: '0.4rem'}}>Email</label>
                <br />
                <Input 
                    placeholder="Enter email"
                    type="email"
                    isFullWidth={true}
                    disabled={loading}
                    isInvalid={emailError.length > 0}
                    value={email}
                    onChange={e => {setEmail(e.target.value)}}
                />

                {emailError.length > 0 && !loading && <Message type="error" message={emailError}></Message>}
                
                <label style={{ marginLeft: '0.4rem'}}>Password</label>
                <br />
                <Input 
                    placeholder="Enter password"
                    type="password"
                    isFullWidth={true}
                    disabled={loading}
                    isInvalid={passwordError.length > 0}
                    value={password}
                    onChange={e => {setPassword(e.target.value)}}
                />

                {passwordError.length > 0 && !loading && <Message type="error" message={passwordError}></Message>}
                
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button onClick={submit} isLoading={loading} isFullWidth={width < 500}>Submit</Button>
                </div>
            </div>
        </>
    );
}