import { useDispatch, useSelector } from 'react-redux';
import AppNavbar from '../navigation/app-navbar';
import Sidebar from '../navigation/sidebar/sidebar';
import { Redirect, useParams } from 'react-router-dom';
import { actions as uiActions } from '../../store/ui';
import TextBasedChannel from '../channel/text-based-channel';
import { useEffect } from 'react';
import PageWrapper from './page-wrapper';
import { getDMChannel, createDM } from '../../store/channels';
import WSListener from '../ws-listener';
import DMList from '../navigation/sidebar/dm-list';

const DMPage: React.FunctionComponent = () => {  
  const { channelId }: any = useParams();
  const dispatch = useDispatch();
  const channel = useSelector(getDMChannel(channelId));
  const users = useSelector((s: Store.AppState) => s.entities.users);
  const selfUser = useSelector((s: Store.AppState) => s.auth.user)!;
  const ui = useSelector((s: Store.AppState) => s.ui);

  useEffect(() => {
    if (!channel && channelId) {
      const otherUser = users.find(u => u.id === channelId);
      if (otherUser) {
        dispatch(createDM(otherUser.id));
      }
    }
    dispatch(uiActions.pageSwitched({ channel }));
  }, [channel, channelId]);

  if (!channel && !channelId) 
    return <Redirect to="/channels/@me" />;

  const otherUser = users.find(u => 
    channel?.type === 'DM' && channel.userIds.includes(u.id) && u.id !== selfUser.id);

  return (
    <PageWrapper pageTitle={otherUser?.username ?? 'Direct Messages'}>
      <WSListener />
      <div className="flex">
        <Sidebar />
        <div className="bg-bg-primary flex-1">
          <AppNavbar />
          <div
            style={{ height: 'calc(100vh - 48px)' }}
            className="flex">
            {channel && ui.activeChannel && {
              'DM': <TextBasedChannel />,
            }[channel.type]}
            <DMList />
          </div>
        </div>
      </div>
    </PageWrapper>
  );
}

export default DMPage;