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

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 = localStorage.getItem("user");

                if (userData) {
                    const parsedData = JSON.parse(userData);
                    setUserName(`${parsedData.firstName} ${parsedData.lastName}`);
                } else {
                    const data = await getCurrentUser();
                    setUserName(`${data.firstName} ${data.lastName}`);
                }
            } catch (error) {
                console.error("Ошибка загрузки данных пользователя:", error);
            } 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;