import React, { useState } from "react";
import "./index.less";
import Header from "../../components/Header";
import { Form, Input, Button, Checkbox, Row, Col, notification } from "antd";
import _auth from "@netuno/auth-client";
import { Redirect } from "react-router-dom";

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 2, span: 16 },
};

const Login = () => {
  const [isLogged, setIsLogged] = useState(false);
  const onFinish = (values) => {
    _auth.login({
      username: values.username,
      password: values.password,
      success: () => {
        setIsLogged(true);
        if (values.remember) {
          localStorage.setItem("login", JSON.stringify(values));
        } else {
          localStorage.removeItem("login");
        }
      },
      fail: () => {
        notification["error"]({
          message: "Ocorreu um erro",
          description: "Não foi possível realizar o login.",
        });
      },
    });
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  let initialValues = {
    remember: true,
  };
  if (localStorage.getItem("login")) {
    initialValues = JSON.parse(localStorage.getItem("login"));
  }
  if (_auth.isLogged()) {
    return <Redirect to="/main" />;
  }
  return (
    <div className="login">
      <Header />
      <Row justify="start" style={{ padding: "12% 20px" }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Form
            {...layout}
            initialValues={initialValues}
            className="login__form"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="Username"
              name="username"
              rules={[
                {
                  required: true,
                  message: "Por favor digite o seu nome de usuário.",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="Senha"
              name="password"
              rules={[
                { required: true, message: "Por favor digite uma senha" },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item {...tailLayout} name="remember" valuePropName="checked">
              <Checkbox>Lembrar dados de login.</Checkbox>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button
                type="primary"
                htmlType="submit"
                className="login__submit"
              >
                Entrar
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    </div>
  );
};

export default Login;
