import React, { useEffect, useState } from 'react';
import styles from './Account.module.css';
import AccountImg from '../../assets/account.svg?react';
import { getCurrentUser } from '../../api/AuthApi';
import {handleUnauthorizedError} from "../../api/BaseApi.ts";

interface AccountProps {
    href: string;
}

const Account: React.FC<AccountProps> = ({ href }) => {
    const [userName, setUserName] = useState<string>();
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchUserData = async () => {
            try {
                const userData = await getCurrentUser();
                setUserName(`${userData.firstName} ${userData.lastName}`);
            } catch (error) {
                handleUnauthorizedError(error)
                console.error("Ошибка загрузки данных пользователя:", error);
                localStorage.removeItem("user");
            } finally {
                setIsLoading(false);
            }
        };

        fetchUserData();
    }, []);

    if (isLoading) {
        return <div className={styles.account}>Загрузка...</div>;
    }

    return (
        <div className={styles.account}>
            <a className={styles.accountText} href={href}>
                <AccountImg className={styles.accountImg}/>
                {userName}
            </a>
        </div>
    );
};

export default Account;