/**
 * 登录页 — 用户名 + 密码表单，居中卡片布局。
 *
 * - 调用 useAuth().login() 进行认证
 * - 成功后跳转 /applications
 * - 401 → "用户名或密码错误"，403 → "账号已被禁用"
 * - 已认证用户访问 /login 时重定向到首页
 */

import React, { useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { Form, Input, Button, Card, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useAuth } from "../../hooks/useAuth";
import type { AxiosError } from "axios";

interface LoginFormValues {
  username: string;
  password: string;
}

const Login: React.FC = () => {
  const { isAuthenticated, login } = useAuth();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  // 已认证用户直接重定向到首页
  if (isAuthenticated) {
    return <Navigate to="/applications" replace />;
  }

  const onFinish = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      await login(values.username, values.password);
      navigate("/applications", { replace: true });
    } catch (err) {
      const axiosErr = err as AxiosError<{ message?: string }>;
      const status = axiosErr.response?.status;
      if (status === 403) {
        message.error("账号已被禁用");
      } else {
        // 401 或其他错误统一提示
        message.error("用户名或密码错误");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        background: "#f0f2f5",
      }}
    >
      <Card
        title="租户管理后台"
        style={{ width: 400 }}
        styles={{ header: { textAlign: "center", fontSize: 20, fontWeight: 600 } }}
      >
        <Form<LoginFormValues>
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <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>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
