import type { FC } from 'react';

import { AvatarProps } from '@material-hu/mui/Avatar';

import { ChatListItem, ChatType } from 'src/types/chats';
import { User } from 'src/types/user';

import FormChatAvatar from './FormChatAvatar';
import GroupChatAvatar from './GroupChatAvatar';
import RegularChatAvatar from './RegularChatAvatar';
import TicketChatAvatar from './TicketChatAvatar';

const avatarByType = {
  [ChatType.REGULAR]: ({
    withLink,
    withUserDeleted,
    thread,
    otherUser,
    ...avatarProps
  }: ChatAvatarProps) => (
    <RegularChatAvatar
      withLink={withLink}
      withUserDeleted={withUserDeleted}
      otherUser={thread.chat.otherUser || otherUser}
      {...avatarProps}
    />
  ),
  [ChatType.REGULAR_GROUP]: ({
    withLink,
    thread,
    ...avatarProps
  }: ChatAvatarProps) => (
    <GroupChatAvatar
      pictureUrl={thread.pictureUrl}
      color={thread.color}
      {...avatarProps}
    />
  ),
  [ChatType.TICKET]: ({
    withLink,
    thread,
    isChatToolbar = false,
    ...avatarProps
  }: ChatAvatarProps) => (
    <TicketChatAvatar
      ticketId={thread.id}
      topic={thread.topic}
      isChatToolbar={isChatToolbar}
      {...avatarProps}
    />
  ),
  [ChatType.FORM]: ({ thread, ...avatarProps }: ChatAvatarProps) => (
    <FormChatAvatar
      pictureUrl={thread.form.pictureUrl}
      {...avatarProps}
    />
  ),
};

export type ChatAvatarProps = AvatarProps & {
  otherUser?: User;
  thread: ChatListItem;
  withLink?: boolean;
  withUserDeleted?: boolean;
  size?: 'small' | 'medium' | 'large' | number;
  isChatToolbar?: boolean;
};

const ChatAvatar: FC<ChatAvatarProps> = props => {
  const {
    thread: { chatType },
  } = props;

  return chatType && avatarByType[chatType] && avatarByType[chatType](props);
};

export default ChatAvatar;
