import React from 'react'
import { useMsal } from '@azure/msal-react'
import { FaUserCircle } from 'react-icons/fa'
import styles from './SidebarUser.module.css'

interface User {
    id: number;
    name: string;
    role: string;
}

interface SidebarUserProps {
    user: User;
    isLoading?: boolean;
    error?: string | null;
}

const SidebarUser: React.FC<SidebarUserProps> = ({ user, isLoading, error }) => {
    const { instance } = useMsal();

    const handleLogout = async () => {
        try {
            // Clear MSAL cache and sign out
            await instance.logoutRedirect({
                onRedirectNavigate: () => {
                    // Clear any application-specific data from localStorage
                    localStorage.clear();
                    return true;
                }
            });
        } catch (error) {
            console.error('Logout failed:', error);
        }
    };

    if (isLoading) {
        return <div className={styles.userContainer}>Lädt...</div>;
    }

    if (error) {
        return <div className={styles.userContainer}>Fehler beim Laden des Benutzerprofils</div>;
    }

    return (
        <div className={styles.user_section}>
            <div className={styles.user_info}>
                <FaUserCircle className={styles.user_icon} />
                <div className={styles.text_content}>
                    <h1>{ user.name }</h1>
                    <p>Rolle: {user.role}</p>
                </div>
            </div>
            <button 
                className={styles.logout_button}
                onClick={handleLogout}
            >
                Logout
            </button>
        </div>
    )
}

export default SidebarUser;