import { Loading3QuartersOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { Button, Checkbox, Flex, Form, Input } from 'antd';
import { NavLink, useNavigate } from 'react-router';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { loginUser } from './authSlice';
import { useEffect } from 'react';
import useMessage from 'antd/es/message/useMessage';

// 定义 Form 表单的字段类型
interface FormValues {
    email: string;
    password: string;
    remember: boolean;
}

function Login() {
    const dispatch = useAppDispatch();
    const auth = useAppSelector(state => (state.auth));
    const [messageApi, Message] = useMessage()
    const nav = useNavigate()

    useEffect(() => {
        if (auth.isAuth) {
            nav('/', { replace: true });
        }
        if (!auth.loading && auth.error) {
            messageApi.error(auth.error);
        }
    }, [auth, messageApi, nav])

    // 给 onFinish 参数添加类型
    const onFinish = async (values: FormValues) => {
        try {
            await dispatch(loginUser({ email: values.email, password: values.password }));
        } catch (error) {
            console.error('登录失败', error);
        }
    };

    return (
        <Form
            name="login"
            initialValues={{ remember: true }}
            onFinish={onFinish}
        >
            {Message}
            <h2>登录</h2>
            <Form.Item
                name="email"
                rules={[{ required: true, message: '请输入你的账号（注册邮箱）！' }, { type: 'email', message: '请输入正确的邮箱' }]}
            >
                <Input prefix={<MailOutlined />} placeholder="账号（注册邮箱）" />
            </Form.Item>
            <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入你的密码！' }]}
            >
                <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item>
                <Flex justify="space-between" align="center">
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                        <Checkbox>自动登录</Checkbox>
                    </Form.Item>
                    <NavLink to="/forget"> 忘记密码 </NavLink>
                </Flex>
            </Form.Item>

            <Form.Item>
                <Button block type="primary" htmlType="submit">
                    {auth.loading ? (
                        <><Loading3QuartersOutlined /></>
                    ) : (
                        <>登录</>
                    )
                    }
                </Button>
                或 <NavLink to="/register">注册</NavLink>
            </Form.Item>
        </Form>
    );
}

export default Login;
