import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Flex, Form, Input, message } from "antd";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { login } from "../features/auth/authThunk";
import roleRoute from "../config/roleRouteConfig";

export default function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const onFinish = async (values) => {
    const res = await dispatch(login(values)).unwrap();
    const path = res.roles.map((r) => roleRoute[r]).find(Boolean);
    if (path) {
      message.success("登录成功");
      navigate(path);
    } else {
      message.error("系统错误");
    }
  };

  return (
    <div className="w-screen h-screen flex justify-center items-center flex-col">
      <h1 className="m-6 text-gray-800 font-mono text-4xl">
        电科院材料所实验室仪器设备预约系统
      </h1>
      <Form
        name="login"
        autoComplete="off"
        initialValues={{ size: "large" }}
        size="large"
        onFinish={onFinish}
        className="w-1/4"
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
        </Form.Item>

        <Flex justify="flex-end">
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Flex>
      </Form>
    </div>
  );
}
