import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { message } from 'antd';
import { getUserInfo, login } from '@/services/api';

const LoginPage: React.FC = () => {
  const { setInitialState } = useModel('@@initialState');

  const handleSubmit = async (values: { username: string; password: string }) => {
    try {
      const res = await login(values);
      if (res.code === 0) {
        localStorage.setItem('token', res.data.token);

        // Important: load authorized menu paths immediately after login.
        // Otherwise, first render may temporarily show full menus until refresh.
        const infoRes = await getUserInfo();
        if (infoRes?.code === 0 && infoRes.data) {
          await setInitialState({
            currentUser: infoRes.data,
            menuPaths: infoRes.data.menuPaths || [],
          });
        } else {
          await setInitialState({
            currentUser: res.data.userInfo,
            menuPaths: [],
          });
        }

        message.success('登录成功');
        history.push('/dashboard');
      } else {
        message.error(res.msg || '登录失败');
      }
    } catch (error) {
      message.error('网络异常，请稍后重试');
    }
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', background: '#f0f2f5' }}>
      <LoginForm
        title="muyuqingfeng仓储管理系统"
        subTitle="Warehouse Management System"
        onFinish={handleSubmit}
      >
        <ProFormText
          name="username"
          fieldProps={{ size: 'large' }}
          placeholder="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{ size: 'large' }}
          placeholder="密码"
          rules={[{ required: true, message: '请输入密码' }]}
        />
      </LoginForm>
    </div>
  );
};

export default LoginPage;
