import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Form, Input, Button, Card, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import api from '../../api';
import { BrandLogo } from '../../components/BrandLogo';
import { message } from '../../ui/app-message';
import { findRoleAwareLandingPath } from '../../auth/menu-policy';
import { usePermissionStore } from '../../store/permission/permissionStore';
import { useUserStore } from '../../store/user/userStore';

const { Title } = Typography;

const LoginPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const setSession = useUserStore((state) => state.setSession);
  const clearPermissions = usePermissionStore((state) => state.clearPermissions);
  const writePermissions = usePermissionStore((state) => state.writePermissions);

  // 会话过期被登出（如 AI 流式请求 401）后回到登录页时给出提示
  useEffect(() => {
    if (sessionStorage.getItem('login_expired_hint')) {
      sessionStorage.removeItem('login_expired_hint');
      message.warning('登录已过期，请重新登录');
    }
  }, []);

  const onFinish = useCallback(
    async (values: any) => {
      clearPermissions();
      setLoading(true);
      try {
        const res: any = await api.post('/auth/login', values);
        setSession(res.access_token, res.user);
        const permissions = res.user.permissions || [];
        writePermissions(permissions);
        message.success('登录成功');
        navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', {
          replace: true,
        });
      } catch (err: any) {
        message.error(err?.message || '登录失败');
      } finally {
        setLoading(false);
      }
    },
    [clearPermissions, navigate, setSession, writePermissions],
  );

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#f5f5f7',
      }}
    >
      <Card
        style={{
          maxWidth: 400,
          width: 'calc(100vw - 48px)',
          borderRadius: 16,
          boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
          border: 'none',
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <BrandLogo size={48} />
          <Title
            level={3}
            style={{ margin: '14px 0 0', fontWeight: 600, color: '#1d1d1f' }}
          >
            学生管理系统
          </Title>
          <p style={{ color: '#86868b', marginTop: 8 }}>学生综合管理平台</p>
        </div>
        <Form name="login" layout="vertical" onFinish={onFinish} size="large">
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              autoComplete="current-password"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{ height: 44, borderRadius: 10, fontWeight: 500 }}
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage;
