import React, { useEffect } from 'react';
import { useApi } from '@/hooks/request';
import request from '@/utils/request';
import { postUserLogin} from '@/api/auth';
import { useAppDispatch } from '@/hooks/store';
import { RootState } from '@/store';
import style from './login.module.css';
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router';
import logo from '&/assets/logo.png';
import { getUserInfo } from '@/api/user';
import debounce from 'lodash/debounce';

const Login: React.FC = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const dispatch = useAppDispatch();
    const { refresh: postUserLoginRefresh } = useApi(() => request.post(postUserLogin, {}), false);
    const { refresh: getUserInfoRefresh } = useApi(() => request.get(getUserInfo), false);

    const nav = useNavigate();
    const handleLogin = debounce(async () => {
        try {
            const res =await postUserLoginRefresh();
            if (res==null ||(res as any).error) {
                alert('Login failed. Please check your credentials.');
                return;
            }
            dispatch({ type: "user/login", payload: res });
            
            const userInfo = await getUserInfoRefresh();
            if (userInfo==null || (userInfo as any).error) {
                alert('Failed to fetch user information.');
                return;
            }
            dispatch({ type: "user/getUserInfo", payload: userInfo });
            nav('/');
        } catch (error) {
            alert('An unexpected error occurred. Please try again later.');
            if (error instanceof Error) {
              console.error(error.message); // 明确访问 message 属性
            } else {
              console.error('Unknown error occurred');
            }
        }
    }, 1000) as () => void;

    const handleLogoClick = () => {
        nav('/');
    }
    return (
        <div className={style.form}>
            <img className={style.logo} src={logo} alt="logo" onClick={handleLogoClick}></img>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={style.email} placeholder="Enter your email" />
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className={style.password} placeholder="Enter your password" />
            <button className={style.submit} onClick={() => handleLogin()}>登录</button>
            <button className={style.register}>注册</button>
            <button className={style.forget}> 忘记密码</button>
        </div>
    );
};

export default Login;