import { Drawer } from 'antd';
import produce from 'immer';
import React, { useEffect, useState } from 'react';
import { useMediaQuery } from 'react-responsive';

import AddUserModal from './components/ChatModal';
import MessageInput from './components/index';
import MessageHeader from './components/MessageHeader';
import MessageList from './components/MessageList';
import RoomList from './components/RoomList';
import { useChannel } from './hooks/useWebSocket';
import { getRoom, patchUpdateRoom } from './services/chat';
import styles from './style.module.css';
import { xs } from './utils/responsive';

type PropType = {
  username: string;
  room_id: string;
  to: (room_id?: string) => void;
  user_id: string;
  members: any[];
  qiniu_url: string;
};

const ChatRoom: React.FC<PropType> = ({ room_id, username, to, user_id, members, qiniu_url }) => {
  const isXs = useMediaQuery(xs);
  const [chat, setChat] = useState<any>({});
  const [visible, setVisible] = useState<boolean>(false);
  const [addVisible, setAddVisible] = useState<boolean>(false);
  const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
  const [indeterminate, setIndeterminate] = React.useState<boolean>(false);
  const [checkAll, setCheckAll] = React.useState<boolean>(false);

  const onCheckAllChange = (e) => {
    setSelectedUserIds(
      e.target.checked
        ? members.filter((s) => chat.room?.allow_user_ids.every((i) => i !== s.user_id)).map((v) => v.user_id)
        : []
    );
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  useChannel(
    `chat-room-record-${username}`,
    username,
    (obj) => {
      const { data } = obj;
      if (data.room_id !== room_id) {
        return;
      }
      if (data.message) {
        setChat(
          produce((draft: any) => {
            draft.records = chat.records.concat([data]);
          })
        );
      }
    },
    { room_id }
  );

  useEffect(() => {
    if (room_id) {
      getRoom(username, room_id)
        .then((res) => {
          setChat(
            produce((draft: any) => {
              draft.records = res.records;
              draft.room = res.room;
              draft.onlineUserIDs = res.online_user_ids;
            })
          );
        })
        .catch(() => {
          to();
        });
    }
  }, [room_id, to, username]);

  const checked = (v) => {
    return chat.room
      ? selectedUserIds.includes(v.user_id) || chat.room.allow_user_ids.some((i) => i === v.user_id)
      : false;
  };

  const disabled = (v) => {
    return chat.room ? chat.room.allow_user_ids.some((i) => i === v.user_id) : true;
  };

  return (
    <div className={styles.chatContainer}>
      <div />
      <div className={styles.roomContainer}>
        {isXs ? (
          <div className={styles.roomListDrawer}>
            <Drawer
              closable={false}
              getContainer={false}
              visible={false}
              placement="left"
            >
              <RoomList
                members={members}
                user_id={user_id}
                chat={chat}
                onChatSet={setChat}
                username={username}
                room_id=""
                to={to}
              />
            </Drawer>
          </div>
        ) : (
          <div className={styles.chatListContainer}>
            <div className={styles.chatListContainer}>
              <div className={styles.chatList}>
                <RoomList
                  members={members}
                  user_id={user_id}
                  chat={chat}
                  onChatSet={setChat}
                  username={username}
                  room_id={room_id}
                  to={to}
                />
              </div>
            </div>
          </div>
        )}
        <div className="flex h-full overflow-hidden">
          <div className={styles.messagePanel}>
            <MessageHeader
              username={username}
              setAddVisible={setAddVisible}
              visible={visible}
              setVisible={setVisible}
              chat={chat}
              onChatSet={setChat}
              members={members}
            />
            <MessageList user_id={user_id} chat={chat} members={members} />
            <div className={styles.messageInput}>
              <MessageInput qiniu_url={qiniu_url} roomId={room_id} username={username} members={members} />
            </div>
          </div>
        </div>
      </div>
      <AddUserModal
        members={members}
        visible={addVisible}
        setVisible={setAddVisible}
        onCheckAllChange={onCheckAllChange}
        indeterminate={indeterminate}
        checkAll={checkAll}
        allowUserIds={selectedUserIds}
        setAllowUserIds={setSelectedUserIds}
        checked={(v) => checked(v)}
        disabled={(v) => disabled(v)}
        title="添加成员"
        okText="增加"
        defaultValue={chat.room ? chat.room.name : ''}
        onOk={() => {
          if (chat.room) {
            setChat(
              produce((draft: any) => {
                if (draft.room) {
                  draft.room.allow_user_ids = chat.room.allow_user_ids.concat(selectedUserIds);
                }
              })
            );
            patchUpdateRoom(
              username,
              chat.room.id,
              chat.room.name,
              selectedUserIds.concat(chat.room.allow_user_ids)
            ).then(() => {
              setVisible(false);
              setAddVisible(false);
              setSelectedUserIds([]);
            });
          }
        }}
      />
    </div>
  );
};

export default ChatRoom;
