import { Badge, Comment, Image, List } from 'antd';
import _ from 'lodash';
import React, { useEffect } from 'react';
import Emoji from 'react-emoji-render';

import styles from '../style.module.css';
import dayjs from '../utils/dayjs';
import CustomizedAvatar from './CustomizedAvatar';
import Markdown from './Markdown';
import UserInfoPop from './UserInfoPop';

type PropType = {
  user_id: string;
  chat: any;
  members: any[];
};

const MessageList: React.FC<PropType> = ({ user_id, chat, members }) => {
  const userProfile = (item) => {
    return members.filter((v) => v.user_id === item.from_user_id)[0];
  };

  const chatMessage = (messageType, v) => {
    switch (messageType) {
      case 'mention':
        return (
          <UserInfoPop chat={chat} user={members.filter((u) => u.user_id === v.user_id)[0]}>
            <div className="cursor-pointer text-blue-400">{v.text}&nbsp;</div>
          </UserInfoPop>
        );
      case 'text':
        return <Markdown content={v.text} />;
      case 'emoicon':
        return <Emoji text={v.text} />;
      case 'attachment':
        return (
          <div className={styles.messageImage}>
            <Image src={v.source_url} preview={false} />
          </div>
        );
      default:
        return null;
    }
  };

  useEffect(() => {
    const scrollDiv = document.getElementById('chatlist');
    const scrollToBottom = () => {
      if (scrollDiv) {
        scrollDiv.scrollIntoView({ block: 'end' });
      }
    };
    scrollToBottom();
  }, [chat.room]);

  return (
    <div className={styles.messageList}>
      <List
        id="chatlist"
        dataSource={chat.records}
        renderItem={(item: any) => (
          <li key={item.id}>
            <Comment
              author={<span className="mb-2">{item.from_user_name}</span>}
              avatar={
                item.from_user_avatar && (
                  <UserInfoPop chat={chat} user={userProfile(item)}>
                    <CustomizedAvatar src={item.from_user_avatar} className="ml-4" />
                    {_.includes(chat.onlineUserIDs, item.from_user_id) && <Badge dot className={styles.onlineDot} />}
                  </UserInfoPop>
                )
              }
              content={
                <div className={`${user_id === item.from_user_id ? styles.myChatMessage : styles.chatMessage}`}>
                  <div className="flex flex-wrap">
                    {item.message.map((v, index) => (
                      <div key={Number(index)} className={v.type === 'attachment' ? 'float-left w-full' : ''}>
                        {chatMessage(v.type, v)}
                      </div>
                    ))}
                  </div>
                </div>
              }
              datetime={item.created_at && dayjs(item.created_at).fromNow()}
            />
          </li>
        )}
      />
    </div>
  );
};

export default MessageList;
