import { message, notification } from "antd";
import { ILoginValues } from "../components/user/login";
import { userReq } from "../request/user";
import { normalizeError } from "../util/util";
import { Login as LoginComponent } from '../components/user/login';
import { useLocation, useNavigate } from "react-router-dom";
import React from "react";

function useQuery() {
    const { search } = useLocation();

    return React.useMemo(() => new URLSearchParams(search), [search]);
}

export default function Login() {
    const navigate = useNavigate();
    const query = useQuery();
    const target = query.get('target');

    const onLogin = (values: ILoginValues) => {
        const { username, password } = values;
        if (!username || !password) {
            message.info('Please fill in your username and password!', 1);
            return;
        }

        userReq.login(username, password).then(() => {
            message.success('Login successful!');
            navigate(target ?? '/');
        }).catch((e) => {
            notification.error({
                message: 'Login failed\n',
                description: normalizeError(e)
            });
        });
    };

    const onSignUp = (values: ILoginValues) => {
        const { username, password } = values;

        if (!username || !password) {
            message.info('Please fill in your username and password!', 1);
            return;
        }

        userReq.signup(username, password).then(() => {
            message.success('Registration successful!', 1);
        }).catch((e) => {
            notification.error({
                message: 'Registration failed',
                description: normalizeError(e)
            });
        });
    };

    return (
        <div style={{ width: "100%", display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <LoginComponent onLogin={onLogin} onSignUp={onSignUp} />
        </div>
    );
}