import React, { useState, useEffect } from "react";

import { Form, Input, Button, Checkbox } from 'antd';

import _auth from '@netuno/auth-client';

import { Redirect } from "react-router-dom";

import './index.less';

const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

export default () => {
    const [ loading, setLoading ] = useState(false);
    const onFinish = (values) => {
        setLoading(true);
        _auth.login({
            username: values.username,
            password: values.password,
            success: ()=> {
                setLoading(false);
            },
            fail: ()=> {
                alert("Fail.");
            }
        });
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    if (_auth.isLogged()) {
        return <Redirect to="/main"/>;
    }
    return (
        <div>
            <h1>Login</h1>
            <div className="login">
                <Form
                    {...layout}
                    name="basic"
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    >
                    <Form.Item
                        label="Username"
                        name="username"
                        rules={[
                        {
                            required: true,
                            message: 'Please input your username!',
                        },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="Password"
                        name="password"
                        rules={[
                        {
                            required: true,
                            message: 'Please input your password!',
                        },
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item {...tailLayout} name="remember" valuePropName="checked">
                        <Checkbox>Relembrar o acesso.</Checkbox>
                    </Form.Item>

                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit" loading={loading}>
                        Entrar
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};
