import { Comment, Drawer, Input, List, Tag } from 'antd';
import produce from 'immer';
import _ from 'lodash';
import React, { useState } from 'react';

import { patchUpdateRoom } from '../services/chat';
import styles from '../style.module.css';
import CustomizedAvatar from './CustomizedAvatar';
import IconFont from './IconFonts';
import UserInfoPop from './UserInfoPop';

type PropType = {
  username: string;
  setAddVisible: (addVisible: boolean) => void;
  visible: boolean;
  setVisible: (visible: boolean) => void;
  chat: any;
  onChatSet: (chat: any) => void;
  members: any[];
};

const MessageHeader: React.FC<PropType> = ({
  username,
  setAddVisible,
  visible,
  setVisible,
  chat,
  onChatSet,
  members,
}) => {
  const [editing, setEditing] = useState<boolean>(false);
  const [filteredUser, setFilteredUser] = useState<string>('');

  return (
    <>
      <div className={styles.messageHeader}>
        <div className={styles.messageHeaderMenu} >
          <IconFont icon="icon-menu" />
        </div>
        {chat.room && [
          <div key="title" className={styles.messageHeaderTitle} onDoubleClick={() => setEditing(true)}>
            {editing ? (
              <Input
                defaultValue={chat.room.name || '未命名'}
                bordered={false}
                onChange={(e) => {
                  onChatSet(
                    produce(chat, (draft) => {
                      draft.room.name = e.target.value;
                    })
                  );
                }}
                autoFocus
                onPressEnter={() => {
                  if (chat.room) {
                    patchUpdateRoom(username, chat.room.id, chat.room.name, chat.room.allow_user_ids).then(() =>
                      setEditing(false)
                    );
                  }
                }}
                onBlur={() => {
                  setEditing(false);
                }}
              />
            ) : (
              <div>
                {chat.room.name || '未命名'}（{chat.room.allow_user_ids.length} ）
                <IconFont
                  icon="icon-pencil-edit"
                  className={styles.editIcon}
                  onClick={() => {
                    setEditing(true);
                  }}
                />
              </div>
            )}
          </div>,
          <div key="add-member">
            <IconFont
              icon="icon-ellipsis-options-vertical"
              className="cursor-pointer pr-4 text-xl font-bold"
              onClick={() => setVisible(!visible)}
            />
          </div>,
        ]}
      </div>
      {chat.room && (
        <Drawer
          visible={visible}
          onClose={() => setVisible(false)}
          forceRender
          width={240}
          drawerStyle={{ borderLeft: '1px solid var(--gray-100)' }}
          getContainer={false}
          closable={false}
          mask={false}
          className={styles.userlistDrawer}
        >
          <div className={styles.searchInputContainer}>
            <Input
              className={styles.searchInput}
              placeholder="搜索"
              allowClear
              onChange={(e) => setFilteredUser(e.target.value)}
              suffix={<IconFont icon="icon-plus" className={styles.addRoomIcon} onClick={() => setAddVisible(true)} />}
            />
          </div>
          <List
            dataSource={_.sortBy(
              members.filter((v) => v.user_name.includes(filteredUser)),
              (a) => a.user_id !== chat.room?.creator_id
            )}
            renderItem={(item: any) => (
              <li key={item.id} className="flex items-center leading-loose">
                <Comment
                  avatar={
                    <UserInfoPop chat={chat} user={members.filter((u) => u.user_id === item.user_id)[0]}>
                      <CustomizedAvatar src={item.avatar} className="ml-4" />
                    </UserInfoPop>
                  }
                  content={
                    <span>
                      {item.user_name}
                      {chat.room?.creator_id === item.user_id && (
                        <Tag className="ml-2" color="green">
                          群主
                        </Tag>
                      )}
                    </span>
                  }
                />
              </li>
            )}
          />
        </Drawer>
      )}
    </>
  );
};

export default MessageHeader;
