import React, { useState, useEffect } from "react";
import "./index.less";
import Header from "../../components/Header";
import { Form, Input, Button, Select, Row, Col, notification } from "antd";
import _service from "@netuno/service-client";

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

const Register = () => {
  const [componentSize, setComponentSize] = useState("default");
  const [cities, setCities] = useState([]);
  useEffect(() => {
    _service({
      url: "cities",
      method: "GET",
      success: (response) => {
        setCities(response.json);
      },
    });
  }, []);
  const onFormLayoutChange = ({ size }) => {
    setComponentSize(size);
  };
  const onFinish = (values) => {
    _service({
      url: "register",
      method: "POST",
      data: values,
      success: (response) => {
        const { result, error } = response.json;
        if (result === true) {
          notification["success"]({
            message: "Sua conta foi criada com sucesso :)",
            description: "Você já pode efutuar o login.",
          });
        } else {
          if (error === "email-exists") {
            notification["error"]({
              message: "E-mail existente",
              description: "O e-mail já foi cadastrado.",
            });
          } else if (error === "user-exists") {
            notification["error"]({
              message: "Nome de usuário indisponível",
              description: "O nome de usuário já está sendo utilizado.",
            });
          }
        }
      },
      fail: () => {
        notification["error"]({
          message: "Erro",
          description: "Não foi possível realizar o cadastro :(",
        });
      },
    });
  };
  const onFinishFailed = (error) => {
    console.log("Failed:", error);
  };
  return (
    <div className="register">
      <Header />
      <Row justify="start" style={{ padding: "5% 20px" }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
            name="basic"
            layout="horizontal"
            initialValues={{ size: componentSize }}
            onValuesChange={onFormLayoutChange}
            size={componentSize}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="Nome"
              name="firstname"
              rules={[
                {
                  required: "true",
                  message: "Campo obrigatório.",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="Sobrenome"
              name="lastname"
              rules={[
                {
                  required: "true",
                  message: "Campo obrigatório.",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="E-mail"
              name="email"
              rules={[
                { type: "email", message: "Utilize um e-mail válido." },
                {
                  required: true,
                  message: "Campo obrigatório.",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="Usuário"
              name="username"
              rules={[
                {
                  required: "true",
                  message: "Campo obrigatório.",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="Senha"
              name="password"
              rules={[
                {
                  required: true,
                  message: "Campo obrigatório",
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="Cidade"
              name="city_uid"
              rules={[
                {
                  required: "true",
                  message: "Campo obrigatório.",
                },
              ]}
            >
              <Select>
                {cities.map((city) => {
                  return (
                    <Select.Option key={city.uid} value={city.uid}>
                      {city.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button
                type="primary"
                htmlType="submit"
                className="register__submit"
              >
                Registrar
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    </div>
  );
};

export default Register;
