import type { FC } from 'react';

import { TypographyProps } from '@material-hu/mui/Typography';

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

import FormChatName from './FormChatName';
import GroupChatName from './GroupChatName';
import RegularChatName from './RegularChatName';
import TicketChatName from './TicketChatName';

const nameByType = {
  [ChatType.REGULAR]: ({
    withLink,
    withUserDeleted,
    thread,
    otherUser,
    ...typographyProps
  }: ChatNameProps) => (
    <RegularChatName
      withLink={withLink}
      withUserDeleted={withUserDeleted && otherUser?.deleted}
      otherUser={thread?.chat?.otherUser || otherUser}
      {...typographyProps}
    />
  ),
  [ChatType.REGULAR_GROUP]: ({
    withLink,
    thread,
    otherUser,
    subtitle,
    ...typographyProps
  }: ChatNameProps) => (
    <GroupChatName
      title={thread.title}
      subtitle={subtitle}
      {...typographyProps}
    />
  ),
  [ChatType.TICKET]: ({
    withLink,
    thread,
    otherUser,
    isChatToolbar = false,
    ...typographyProps
  }: ChatNameProps) => (
    <TicketChatName
      withLink={withLink}
      ticketId={thread.id}
      otherUser={thread.chat.otherUser || otherUser}
      topic={thread.topic}
      isChatToolbar={isChatToolbar}
      {...typographyProps}
    />
  ),
  [ChatType.FORM]: ({
    thread,
    withLink,
    otherUser,
    ...typographyProps
  }: ChatNameProps) => (
    <FormChatName
      formData={thread.form}
      title={thread.form.title}
      otherUser={thread.chat.otherUser || otherUser}
      status={thread.status}
      withProgressStatus={thread.form.withInProgressStatus}
      {...typographyProps}
    />
  ),
};

export type ChatNameProps = TypographyProps & {
  otherUser?: User;
  thread: ChatListItem;
  withLink?: boolean;
  withUserDeleted?: boolean;
  isChatToolbar?: boolean;
  subtitle?: string;
};

const ChatName: FC<ChatNameProps> = props => {
  const {
    thread: { chatType },
  } = props;

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

export default ChatName;
