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

function LoginForm() {
  const signinError = useStore(signinError$);
  const signinLoading = useStore(signinLoading$);

  const onFinish = (values) => {
    signin(values);
  };

  return (
    <Space direction="vertical" style={{ width: "320px" }}>
      {signinError.length > 0 ? (
        <Alert type="error" showIcon closable description={signinError} />
      ) : null}
      <Typography.Title level={4}>Вход</Typography.Title>

      <Form
        disabled={signinLoading}
        name="basic"
        layout="vertical"
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="Логин"
          name="login"
          rules={[{ required: true, message: "Обязательное поле" }]}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="логин"
          />
        </Form.Item>

        <Form.Item
          label="Пароль"
          name="password"
          rules={[{ required: true, message: "Обязательное поле" }]}
        >
          <Input
            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="/register">Регистрация</Link>
        </div>
      </Form>
    </Space>
  );
}

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

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