import React, { useRef, useState, useEffect } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useImageProxy } from '@/hooks/useImageProxy';
import { Button } from 'primereact/button';
import { Menu } from 'primereact/menu';
import useWindowWidth from '@/hooks/useWindowWidth';
import {useSession, signOut} from 'next-auth/react';
import { Dialog } from 'primereact/dialog';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import styles from '../navbar.module.css';

const UserAvatar = () => {
    const router = useRouter();
    const [isClient, setIsClient] = useState(false);
    const [user, setUser] = useState(null);
    const [visible, setVisible] = useState(false);
    const { returnImageProxy } = useImageProxy();
    const windowWidth = useWindowWidth();

    const { data: session, status } = useSession();

    useEffect(() => {
        if (session) {
            console.log(session);
            setUser(session.user);
        }
    }, [session]);

    const menu = useRef(null);

    const handleLogout = async () => {
        await signOut({ redirect: false }); // Wait for the sign-out to complete
        router.push('/').then(() => window.location.reload());
    }

    let userAvatar;

    useEffect(() => {
        setIsClient(true); // Component did mount, we're client-side
    }, []);

    // If not client, render nothing or a placeholder
    if (!isClient) {
        return null; // Or return a loader/spinner/placeholder
    } else if (user && Object.keys(user).length > 0) {
        // User exists, show username or pubkey
        const displayName = user.username || user.pubkey.slice(0, 10) + '...';

        const items = [
            {
                label: displayName,
                items: [
                    {
                        label: 'Profile',
                        icon: 'pi pi-user',
                        command: () => router.push('/profile')
                    },
                    {
                        label: 'Create',
                        icon: 'pi pi-book',
                        command: () => router.push('/create')
                    },
                    {
                        label: 'Logout',
                        icon: 'pi pi-power-off',
                        command: handleLogout
                    }
                ]
            }
        ];
        userAvatar = (
            <>
                <div onClick={(event) => menu.current.toggle(event)} className='flex flex-row items-center justify-between cursor-pointer hover:opacity-75'>
                    <Image
                        alt="logo"
                        src={returnImageProxy(user.avatar, user.pubkey)}
                        width={50}
                        height={50}
                        className={styles.logo}
                    />
                </div>
                <Menu model={items} popup ref={menu} />
            </>
        );
    } else {
        userAvatar = (
            <div className='flex flex-row items-center justify-between'>
            <Button severity='help' rounded label="About" className='text-[#f8f8ff] mr-4' onClick={() => setVisible(true)} />
            <Dialog header="Header" visible={visible} style={{ width: '50vw' }} onHide={() => {if (!visible) return; setVisible(false); }}>
                <p className="m-0">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
                    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
                    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </p>
            </Dialog>
            <Button
                label="Login"
                icon="pi pi-user"
                className="text-[#f8f8ff]"
                rounded
                onClick={() => router.push('/auth/signin')}
                size={windowWidth < 768 ? 'small' : 'normal'}
                />
            </div>
        );
    }

    return userAvatar;
};

export default UserAvatar;
