import React, { useCallback, useState } from 'react';
import styled from 'styled-components';
import { Button } from 'reactstrap';
import { toast } from 'react-toastify';
import { useHistory } from 'react-router-dom';
import BaseSpinner from 'react-loader-spinner';

import { login } from '../services/auth';
import { useMemo } from 'react';
import useQueryParams from '../hooks/useQueryParams';

const Spinner = styled(BaseSpinner)`
    display: inline-flex;
    margin: 0 10px;
`;

const Container = styled.div`
    max-width: 1024px;
    margin: 0 auto;
    width: 100%;
`;
const Wrapper = styled(Container)`
    background-color: #ffffff;
    color: #3e4457;
    padding: 20px 60px 120px 60px;
`;
const Section = styled.div`
    align-items: center;
    display: flex;
    flex-direction: row;
    margin: 20px auto;
    padding: 20px 0;
`;
const Input = styled.input`
    border-radius: 24px;
    border: 3px solid #cccccc;
    box-sizing: content-box;
    flex-grow: 1;
    font-size: 22px;
    height: 30px;
    outline: none;
    padding: 10px 20px;

    &:focus {
        border-color: #3e4457;
    }
`;
const Label = styled.label`
    color: #3e4457;
    font-size: 32px;
    margin-right: 10px;
    width: 100px;
`;
const LoginButton = styled(Button)`
    float: right;
    font-size: 32px;
    padding: 15px 20px;
    width: 250px;
`;

const canSubmit = (formData: FormData) => {
    if (!formData.get('email')) {
        return false;
    }
    if (!formData.get('password')) {
        return false;
    }
    return true;
};

function LoginScreen() {
    const [isLoading, setLoading] = useState(false);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const history = useHistory();
    const queryParams = useQueryParams();

    const formData = useMemo(() => {
        const formData = new FormData();
        formData.set('email', email);
        formData.set('username', email);
        formData.set('password', password);

        return formData;
    }, [email, password]);

    const onChangeEmail = useCallback(
        (event: React.ChangeEvent<HTMLInputElement>) => {
            setEmail(event.target.value);
        },
        [setEmail]
    );
    const onChangePassword = useCallback(
        (event: React.ChangeEvent<HTMLInputElement>) => {
            setPassword(event.target.value);
        },
        [setPassword]
    );

    const onClickLogin = useCallback(async () => {
        setLoading(true);

        try {
            const { firstName } = await login(formData);
            const next = queryParams.get('next');

            history.push(next || '/curadoria');
            toast.success(`Bem vindo, ${firstName}!`);
        } catch (error) {
            console.log(error);
            toast.error(`Erro: ${error.message}`);
        } finally {
            setLoading(false);
        }
    }, [formData, history, queryParams]);

    return (
        <Wrapper>
            <h1>Login - 3d.com.vc</h1>

            <Section>
                <Label>Email</Label>
                <Input onChange={onChangeEmail} value={email} />
            </Section>
            <Section>
                <Label>Senha</Label>
                <Input
                    onChange={onChangePassword}
                    type="password"
                    value={password}
                />
            </Section>
            <LoginButton
                disabled={!canSubmit(formData)}
                color="primary"
                onClick={onClickLogin}
            >
                {isLoading ? 'Entrando' : 'Entrar'}

                {isLoading && (
                    <Spinner type="TailSpin" width={32} height={32} />
                )}
            </LoginButton>
        </Wrapper>
    );
}

export default LoginScreen;
