import {useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import {StackNavigationProp, useHeaderHeight} from '@react-navigation/stack';
import React, {useContext} from 'react';
import {StyleSheet, View} from 'react-native';
import {useSelector} from 'react-redux';
import {
  Channel,
  Chat,
  MessageInput,
  MessageList,
} from 'stream-chat-react-native';
import {ChatContext} from '../../App';
import {MainStackParams} from '../../routes';
import {RootState} from '../../store/rootReducer';

type ChatScreenNavigationProp = StackNavigationProp<MainStackParams, 'Chat'>;
interface ChatScreenProps {
  navigation: ChatScreenNavigationProp;
}
/*
 * Screen that displays all of the user's active conversations.
 */
const ChatScreen: React.FC<ChatScreenProps> = () => {
  const {channel, chatClient} = useContext(ChatContext);
  const headerHeight = useHeaderHeight();
  const tabbarHeight = useBottomTabBarHeight();
  const {userId: loggedInUserId} = useSelector(
    (state: RootState) => state.user.user,
  );
  const otherMembers = channel
    ? Object.values(channel.state.members).filter(
        (member) => member.user?.id !== loggedInUserId,
      )
    : [];
  const member = otherMembers.length === 1 ? otherMembers[0] : undefined;

  return (
    <View style={[styles.container, {paddingBottom: tabbarHeight}]}>
      <Chat client={chatClient}>
        <Channel channel={channel} keyboardVerticalOffset={headerHeight}>
          <MessageList onThreadSelect={() => {}} />
          <MessageInput />
        </Channel>
      </Chat>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
  },
});

export default ChatScreen;
