import { IChatConversation, IChatConversationClient, IChatMessage } from '@/shared/types/chat';

// ----------------------------------------------------------------------

type Props = {
  currentUserId: string;
  conversation: IChatConversationClient;
};

export default function useGetNavItem({ currentUserId, conversation }: Props) {

  if (!conversation) {
    // Handle the case where conversation is undefined, maybe return default values or handle the error
    return {
      messages: [],
      participants: [],
      typeConv: null,
      uuid: '',
    };
  }
  const { messages, participants, typeConv, uuid } = conversation;

  const participantsInConversation = participants.filter(
    (participant) => participant.uuid !== currentUserId
  );

  const lastMessage = [...messages].sort((a: IChatMessage, b: IChatMessage) => a.id - b.id)[messages.length - 1];
  // const lastMessage = messages[messages.length - 1];

  const group = participantsInConversation.length > 2;

  const displayName = participantsInConversation.map((participant) => participant.firstname + " " + participant.lastname).join(', ');

  const hasOnlineInGroup = group
    ? participantsInConversation.map((item) => item.status).includes('online')
    : false;

  let displayText = '';

  if (lastMessage) {
    const sender = lastMessage.owner?.uuid === currentUserId ? 'You: ' : '';

    const message = lastMessage.type === 'image' ? 'Sent a photo' : lastMessage.body;

    displayText = `${sender}${message}`;
  }

  return {
    group,
    displayName,
    displayText,
    participants: participantsInConversation,
    lastActivity: lastMessage?.owner?.lastActivity,
    hasOnlineInGroup,
    typeConv,
    lastMessage //CHANGES
  };
}
