import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { Switch, Route, NavLink } from 'react-router-dom';
import Detail from 'components/routes/Message/Detail';
import InfiniteScroll from 'react-infinite-scroller';
import CreateRoomForm from 'components/forms/CreateRoomForm';
import { Form } from 'react-final-form';
import styleIdentifiers from './message.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type MessageProps = StateProps & DispatchProps & OwnProps;

const Message = (props: MessageProps) => {
  const {
    getRooms,
    rooms,
    dialogShow,
    dialogHide,
    profile,
    getMoreRooms,
    createRoom,
    history,
  } = props;

  function loadRoom() {
    if (rooms && rooms.loading) return;

    if (rooms && rooms.data) {
      getMoreRooms({ skip: rooms.data.length });
    }
  }

  function roomCreation(val) {
    const ids = val.accountIds;
    ids.push(profile.data._id);

    createRoom({
      data: {
        accountIds: ids,
      },
      callback: res => {
        dialogHide('custom');
        history.push(`/message/${res._id}`);
      },
    });
  }

  function dialogCreateRoom() {
    dialogShow({
      id: 'custom',
      children: <Form component={CreateRoomForm} onSubmit={e => roomCreation(e)} />,
    });
  }

  function renderRoomName(room) {
    if (room.getAccounts && profile.data) {
      const people = room.getAccounts.filter(e => e._id !== profile.data._id);
      const unread = room.stats.unreadCounts.filter(e => e.accountId === profile.data._id);
      if (people.length !== 0) {
        return (
          <div className={styles('room-item')}>
            {people.map((item, key) => (
              <span key={key}>
                {key !== 0 && ','}
                {item.userName}
              </span>
            ))}
            {unread && unread[0] && unread[0].count !== 0 && (
              <div className={styles('indic')}>
                {unread[0].count >= 10 ? '9+' : unread[0].count}
              </div>
            )}
          </div>
        );
      }
    }
    return <div>Unknow</div>;
  }

  useEffect(() => {
    getRooms({ skip: 0 });
  }, []);

  const containerScroll = useRef(null);

  return (
    <div className={styles('Message')}>
      <div className={styles('nav-container')}>
        <div className={styles('nav-content')} ref={containerScroll}>
          <InfiniteScroll
            useWindow={false}
            hasMore={rooms && !rooms.noMore}
            pageStart={0}
            loadMore={() => loadRoom()}
            getScrollParent={() => containerScroll.current}
          >
            <div className={styles('nav')}>
              {rooms &&
                rooms.data &&
                rooms.data.map((item, key) => (
                  <div className={styles('item-wrapper')} key={key}>
                    <NavLink
                      to={`/message/${item._id}`}
                      className={styles('item', 'link-wrapper')}
                      activeClassName={styles('state-active')}
                    >
                      {renderRoomName(item)}
                    </NavLink>
                  </div>
                ))}
            </div>
          </InfiniteScroll>
        </div>
        <div className={styles('nav-footer')}>
          <div className={styles('nav-footer-content')} onClick={dialogCreateRoom}>
            <TextItem path="admin.message.addRooms" />
          </div>
        </div>
      </div>
      <Switch>
        <Route exact path="/message/:id" component={Detail} />
      </Switch>
    </div>
  );
};

export default Message;
