import {useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import {StackNavigationProp} from '@react-navigation/stack';
import React, {useContext, useEffect} from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
import {SafeAreaView, useSafeAreaInsets} from 'react-native-safe-area-context';
import {
  Channel,
  Chat,
  DeepPartial,
  MessageInput,
  MessageList,
  useAttachmentPickerContext,
  Theme,
  useMessageContext,
  isDayOrMoment,
  useTranslationContext,
} from 'stream-chat-react-native';
import moment from 'moment';
import {ChatContext} from '../../App';
import {
  ChatHeader,
  ChatInput,
  MessageAvatar,
  TabsGradient,
  TypingIndicator,
} from '../../components';
import {MainStackParams} from '../../routes';
import {ScreenType} from '../../types';
import {HeaderHeight, isIPhoneX, normalize, SCREEN_WIDTH} from '../../utils';

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 tabbarHeight = useBottomTabBarHeight();
  const {setTopInset} = useAttachmentPickerContext();
  const insets = useSafeAreaInsets();
  const chatTheme: DeepPartial<Theme> = {
    colors: {
      accent_blue: '#6EE7E7',
    },
    messageList: {
      container: {
        backgroundColor: 'white',
        width: SCREEN_WIDTH * 0.95,
        alignSelf: 'center',
      },
    },
    messageInput: {
      container: {
        backgroundColor: '#f8f8f8',
        height: 70,
      },
    },
    avatar: {
      container: {
        borderRadius: 10,
        width: normalize(18),
        height: normalize(18),
      },
    },
    messageSimple: {
      avatarWrapper: {
        container: {
          width: normalize(20),
          zIndex: 1,
          bottom: 20,
        },
      },
      container: {
        paddingTop: 8,
        flexDirection: 'row',
      },
      content: {
        deletedContainer: {},
        deletedContainerInner: {
          borderColor: 'transparent',
          borderBottomLeftRadius: 10,
          borderTopLeftRadius: 10,
          borderBottomRightRadius: 10,
          borderTopRightRadius: 10,
        },
        deletedMetaText: {
          paddingHorizontal: 10,
        },
        deletedText: {
          em: {
            fontSize: 15,
            fontStyle: 'italic',
            fontWeight: '400',
          },
        },
        metaContainer: {
          marginLeft: 5,
        },
        container: {},
        containerInner: {
          backgroundColor: '#E4F0F2',
          borderColor: 'transparent',
          borderBottomLeftRadius: 10,
          borderTopLeftRadius: 10,
          borderBottomRightRadius: 10,
          borderTopRightRadius: 10,
        },
      },
      status: {
        statusContainer: {},
      },
    },
  };

  const loggedInUsersMessageTheme = {
    messageSimple: {
      content: {
        containerInner: {
          backgroundColor: '#DEE6F4',
        },
        container: {
          left: 0,
        },
      },
    },
  };

  useEffect(() => {
    setTopInset(insets.top + HeaderHeight);
  });

  const DateHeader = ({date}) => {
    const {tDateTimeParser} = useTranslationContext();

    if (!date) {
      return null;
    }

    const dateFormat =
      date.getFullYear() === new Date().getFullYear() ? 'MMM D' : 'MMM D, YYYY';
    const tDate = tDateTimeParser(date);
    const dateString = isDayOrMoment(tDate)
      ? tDate.format(dateFormat)
      : new Date(tDate).toDateString();

    var dateMoment = moment(dateString);
    var printDate = '';

    const TODAY = moment();
    const YESTERDAY = moment().subtract(1, 'day');
    const LAST_6_DAYS = moment().subtract(6, 'day');

    if (TODAY === dateMoment) {
      printDate = 'Today';
    } else if (YESTERDAY === dateMoment) {
      printDate = 'Yesterday';
    } else if (dateMoment.isBetween(LAST_6_DAYS, YESTERDAY)) {
      printDate = dateMoment.format('dddd');
    } else {
      if (dateMoment.get('year') === 2000) {
        printDate = dateMoment.format('MMMM D') + 'th';
      } else {
        printDate = dateMoment.format('MMMM D, YYYY') + 'th';
      }
    }
    return (
      <View style={{backgroundColor: 'transparent'}}>
        <Text style={styles.dateHeader}>{printDate}</Text>
      </View>
    );
  };

  const MessageFooter = () => {
    const message = useMessageContext();
    if (message.message.type === 'deleted') {
      return <></>;
    } else {
      const printTime = moment(message.message.created_at).format('h:mmA');
      const styles = message.isMyMessage ? {marginRight: 5} : {marginLeft: 5};

      if (message.lastGroupMessage) {
        return (
          <View style={[styles, {marginTop: 4, flexDirection: 'row'}]}>
            {readReceipts(message)}
            <Text
              style={{
                fontSize: normalize(11),
                color: '#7A7A7A',
                lineHeight: normalize(13),
              }}>
              {printTime}
            </Text>
          </View>
        );
      } else {
        return <></>;
      }
    }
  };

  const readReceipts = (message) => {
    const readByLocal = message.message.readBy;
    if (message.isMyMessage) {
      if (readByLocal) {
        return (
          <Image
            source={require('../../assets/icons/messages/read_icon.png')}
            style={{width: 15, height: 15}}
          />
        );
      } else if (message.message.status === 'received') {
        return (
          <Image
            source={require('../../assets/icons/messages/delivered_icon.png')}
            style={{width: 15, height: 15}}
          />
        );
      } else if (message.message.status === 'sending') {
        return (
          <Image
            source={require('../../assets/icons/messages/sent_icon.png')}
            style={{width: 15, height: 15}}
          />
        );
      } else {
        return <></>;
      }
    }
  };

  return (
    <SafeAreaView
      style={[
        styles.container,
        // unable to figure out the padding issue, a hacky solution
        {paddingBottom: isIPhoneX() ? tabbarHeight + 20 : tabbarHeight + 50},
      ]}>
      <ChatHeader screenType={ScreenType.Chat} />
      <Chat client={chatClient} style={chatTheme}>
        <Channel
          channel={channel}
          keyboardVerticalOffset={0}
          OverlayReactionList={() => null}
          messageActions={({copyMessage, deleteMessage}) => [
            copyMessage,
            {
              action: () => deleteMessage?.action,
              title: 'Unsend Message',
              icon: deleteMessage?.icon, // Use some SVG icon here | Optional
              titleStyle: deleteMessage?.titleStyle, // StyleProp<TextStyle> | Optional
            },
          ]}
          InlineDateSeparator={DateHeader}
          StickyHeader={() => null}
          ScrollToBottomButton={() => null}
          MessageFooter={MessageFooter}
          TypingIndicator={TypingIndicator}
          myMessageTheme={loggedInUsersMessageTheme}
          MessageAvatar={MessageAvatar}>
          <MessageList onThreadSelect={() => {}} />
          {/* <MessageInput /> */}
          <MessageInput Input={ChatInput} />
        </Channel>
      </Chat>
      <TabsGradient />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    flex: 1,
  },
  dateHeader: {
    color: '#7A7A7A',
    fontWeight: '600',
    fontSize: normalize(11),
    textAlign: 'center',
    marginVertical: '5%',
  },
});

export default ChatScreen;
