import { IconChevronRight } from '@tabler/icons-react';
import { Avatar, Group, Skeleton, Text, UnstyledButton } from '@mantine/core';
import classes from './UserButton.module.css';
import { useNavigate } from 'react-router-dom';
import { useUserInformation } from '@/app/providers/InformationProvider/useUserInformation';
import { usePublicKey } from '@/app/providers/AccountProvider/usePublicKey';
import { useAvatars } from '@/app/providers/AvatarProvider/useAvatars';

export function UserButton() {
    const navigate = useNavigate();
    const publicKey = usePublicKey();
    const [userInfo] = useUserInformation(publicKey);
    const avatars = useAvatars(publicKey);

    const loading = userInfo.publicKey !== publicKey;

    return (
        <UnstyledButton p={'sm'} className={classes.user} onClick={() => navigate("/main/profile/me")}>
            <Group>
                {!loading && (
                    <>
                        <Avatar
                            radius="xl"
                            name={userInfo.title}
                            color={'initials'}
                            src={avatars.length > 0 ? avatars[0].avatar : undefined}
                        />

                        <div style={{ flex: 1 }}>
                            <Text size="sm" fw={500}>
                                {userInfo.title}
                            </Text>

                            {userInfo.username && (
                                <Text c={'dimmed'} size="xs">
                                    @{userInfo.username}
                                </Text>
                            )}
                        </div>

                        <IconChevronRight size={14} stroke={1.5} />                    
                    </>
                )}
                {loading && (
                    <>
                        <Skeleton height={40} width={40} radius="xl" mr="sm" />
                        <div style={{ flex: 1 }}>
                            <Skeleton height={10} width="80%" mb={6} />
                            <Skeleton height={8} width="40%" />
                        </div>
                        <Skeleton height={14} width={14} />
                    </>
                )}
            </Group>
        </UnstyledButton>
    );
}