import React, { ReactNode, useMemo } from 'react';
import { useAppSelector } from '../stores/hooks';
import UserAvatar from './UserAvatar';

type Props = {
  className?: string;
  children?: ReactNode;
};

export default function UserAvatarCurrentUser({
  className = '',
  children,
}: Props) {
  // Get user data from authSlice.currentUser (single source of truth)
  const { currentUser } = useAppSelector((state) => state.auth);

  // Derive display values from currentUser
  const userName = useMemo(() => {
    if (!currentUser) return '';
    const firstName = currentUser.firstName || '';
    const lastName = currentUser.lastName || '';
    return `${firstName} ${lastName}`.trim() || currentUser.email || '';
  }, [currentUser]);

  const userAvatar = useMemo(() => {
    if (!currentUser?.avatar) return null;
    // avatar can be an array with publicUrl or a direct URL string
    if (Array.isArray(currentUser.avatar) && currentUser.avatar[0]?.publicUrl) {
      return currentUser.avatar[0].publicUrl;
    }
    if (typeof currentUser.avatar === 'string') {
      return currentUser.avatar;
    }
    return null;
  }, [currentUser]);

  // Convert string avatar to array format expected by UserAvatar.image prop
  const imageArray = userAvatar ? [{ publicUrl: userAvatar }] : null;

  return (
    <UserAvatar
      username={userName}
      avatar={userAvatar}
      className={className}
      image={imageArray}
    >
      {children}
    </UserAvatar>
  );
}
