import React, { useEffect } from "react";
import { useAppSelector } from "../../hooks/store";
import style from "./style.module.css"
import { useApi } from "@/hooks/request";
import request from "@/utils/request";
import { getUserInfo } from "@/api/user";
import { useAppDispatch } from "@/hooks/store";

import { useNavigate } from "react-router";


interface SelfStatusProps {
    className?: string;
}

const SelfStatus: React.FC<SelfStatusProps> = () => {

    const nav = useNavigate()
    const userName = useAppSelector(state => state.user.userName);
    const role = useAppSelector(state => state.user.role);
    const uploadTraffic = useAppSelector(state => state.user.uploadTraffic);
    const downloadTraffic = useAppSelector(state => state.user.downloadTraffic);
    const downloadPoints = useAppSelector(state => state.user.downloadPoints);
    const avatar = useAppSelector(state => state.user.avatar);
    const dispatch = useAppDispatch();
    const { data, refresh } = useApi(() => request.get(getUserInfo), false);
    useEffect(() => {
        if (avatar.length === 0) {
            refresh(); // 触发 API 请求
        }
    }, [avatar, refresh]);

    useEffect(() => {
        if (data) {
            dispatch({ type: "user/getUserInfo", payload: data });
        }
    }, [data, dispatch]);

    function handleAvatarClick(){
        nav('/homepage')
    }

    return (
        <div className={style.container}>
            <div className={style.left}>
                {avatar && avatar.length > 0 ? (
                <img className={style.avatar} src={avatar} alt="User Avatar" />):null}
            </div>
            <div className={style.right}>
                <div className={style.info}>
                    <p className={style.userName}>{userName}</p>
                    <p className={style.role}>用户组: {role && role.trim().length? role:'N/A'}</p>
                    <p className={style.uploadTraffic}>上传量: {uploadTraffic ? uploadTraffic : 0}</p>
                    <p className={style.downloadTraffic}>下载量: {downloadTraffic ? downloadTraffic : 0}</p>

                    <p className={style.shareRatio}>
                        分享率: {uploadTraffic && downloadTraffic ? (uploadTraffic / downloadTraffic).toFixed(2) : "N/A"}
                    </p>
                    <p className={style.downloadPoints}>下载积分: {downloadPoints ? downloadPoints : 0}</p>
                </div>
                <button className={style.signInButton}>签到</button>
            </div>
        </div>
    );
};

export default SelfStatus;
