import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, App, Button, Card, Form, Input, Typography } from 'antd';
import { useState } from 'react';
import { Navigate } from 'react-router';
import { useAuth } from '../auth/AuthProvider';

export function LoginPage() {
  const auth = useAuth();
  const { message } = App.useApp();
  const [submitting, setSubmitting] = useState(false);
  if (auth.user) return <Navigate to="/" replace />;

  const submit = async (values: { identifier: string; password: string; newPassword?: string }) => {
    setSubmitting(true);
    try {
      if (auth.challengeToken) await auth.completePasswordChange(values.newPassword || '');
      else await auth.login(values.identifier, values.password);
      message.success('登录成功');
    } catch (error) {
      message.error(error instanceof Error ? error.message : '登录失败');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-brand">
        <img src="/logo.png" alt="恭学题库" />
        <Typography.Title level={1}>恭学题库 SaaS</Typography.Title>
        <Typography.Paragraph>平台运营与资源管理中心</Typography.Paragraph>
      </div>
      <Card className="login-card" variant="borderless">
        <Typography.Title level={3}>{auth.challengeToken ? '设置新密码' : '平台管理员登录'}</Typography.Title>
        {auth.challengeToken && <Alert type="warning" showIcon message="首次登录必须修改密码" className="login-alert" />}
        <Form layout="vertical" size="large" onFinish={submit} requiredMark={false}>
          {!auth.challengeToken && (
            <>
              <Form.Item name="identifier" label="账号" rules={[{ required: true, message: '请输入手机号或账号' }]}>
                <Input prefix={<UserOutlined />} autoComplete="username" placeholder="手机号或账号" />
              </Form.Item>
              <Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
                <Input.Password prefix={<LockOutlined />} autoComplete="current-password" placeholder="登录密码" />
              </Form.Item>
            </>
          )}
          {auth.challengeToken && (
            <Form.Item name="newPassword" label="新密码" rules={[{ required: true }, { min: 8, message: '密码至少 8 位' }]}>
              <Input.Password prefix={<LockOutlined />} autoComplete="new-password" />
            </Form.Item>
          )}
          <Button type="primary" htmlType="submit" block loading={submitting}>{auth.challengeToken ? '设置密码并登录' : '登录'}</Button>
        </Form>
      </Card>
    </div>
  );
}
