import { useStore } from "@nanostores/react";
import { Alert, Button, Form, Input, Result, Space, Typography } from "antd";
import { LockOutlined, MailOutlined, UserOutlined } from "@ant-design/icons";
import React, { useState } from "react";
import { Link, Navigate } from "react-router-dom";
import { isAuthorized$ } from "../stores/auth";
import { register, signupError$, signupLoading$ } from "../stores/signin";

function isObject(obj) {
  var type = typeof obj;
  return type === "function" || (type === "object" && !!obj);
}

function RegisterForm() {
  const [form] = Form.useForm();
  const [successMessage, setSuccessMessage] = useState("");

  const signupError = useStore(signupError$);
  const signupLoading = useStore(signupLoading$);

  const onFinish = (values) => {
    register(values)
      .then(() => {
        setSuccessMessage(
          `Пользователь успешно зарегистрирован. Проверьте почту ${values.email} для активации аккаунта.`
        );
      })
      .catch((e) => {
        if (isObject(e.errors)) {
          form.setFields(e.errors);
        }
      });
  };

  if (successMessage) {
    return (
      <Result
        title={successMessage}
        status="success"
        extra={<Link to="/">На главную</Link>}
      />
    );
  }

  return (
    <Space direction="vertical" style={{ width: "320px" }}>
      {signupError.length > 0 ? (
        <Alert type="error" showIcon closable description={signupError} />
      ) : null}
      <Typography.Title level={4}>Регистрация</Typography.Title>

      <Form
        form={form}
        disabled={signupLoading}
        name="basic"
        layout="vertical"
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          label="Логин"
          rules={[{ required: true, message: "Обязательное поле" }]}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder=""
          />
        </Form.Item>
        <Form.Item
          name="email"
          label="Email"
          rules={[
            {
              required: true,
              type: "email",
              message: "Введите корректный email",
            },
          ]}
        >
          <Input
            type="email"
            autoComplete="email"
            prefix={<MailOutlined className="site-form-item-icon" />}
            placeholder=""
          />
        </Form.Item>

        <Form.Item
          name="password"
          label="Пароль"
          rules={[{ required: true, message: "Обязательное поле" }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            autoComplete="new-password"
            placeholder=""
          />
        </Form.Item>
        <Form.Item
          name="password_confirm"
          label="Пароль еще раз"
          rules={[
            { required: true, message: "Обязательное поле" },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue("password") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error("Пароли не совпадают"));
              },
            }),
          ]}
        >
          <Input
            autoComplete="re-password"
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder=""
          />
        </Form.Item>

        <Form.Item>
          <Button block type="primary" htmlType="submit">
            Зарегистрироваться
          </Button>
        </Form.Item>

        <div style={{ textAlign: "center" }}>
          <Link to="/">Уже есть аккаунт</Link>
        </div>
      </Form>
    </Space>
  );
}

export function RegisterPage() {
  const isAuthorized = useStore(isAuthorized$);

  if (isAuthorized) {
    return <Navigate to="/" replace={true} />;
  } else {
    return (
      <main className="h-screen w-screen flex items-center justify-center">
        <RegisterForm />
      </main>
    );
  }
}
