import moment from 'moment';
import React, { useState, useEffect } from 'react';
import { IConversation } from '../../store/conversations/types';
import { Strings } from '../../resources/localization/Strings';
import { Presence } from '../../store/contacts/types';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { IBubble } from '../../store/bubbles/types';
import { AvatarPresenceBadge } from '../presence/AvatarPresenceBadge';
import { Button, StyleSheet, Text, View } from 'react-native';
import { Avatar, Badge, Divider, TouchableRipple } from 'react-native-paper';

interface IProps {
  conversation: IConversation;
  onClickItem?: (conversation: IConversation) => void;
}


export const ConversationCard: React.FunctionComponent<IProps> = ({ conversation, onClickItem }) => {
  const showLiveMessage = conversation.hasActiveConference;
  const [contactPresence, setContactPresence] = useState<Presence>(conversation.contact?.presence ?? Presence.offline);
  const [conversationState, setConversationState] = useState<IConversation>(conversation);
  useEffect(() => {
    if (conversation.jId !== conversationState.jId) {
      setConversationState(conversation);
    }
    const presenceUpdated = eventEmitter.addListener(
      EventType.PresenceUpdated,
      (eventData: { presence: Presence; contactJId: string }) => {
        if (!conversation.isBubble && conversation.contact?.jId === eventData.contactJId) {
          setContactPresence(eventData.presence);
        }
      }
    );

    const onBubbleUpdated = eventEmitter.addListener(EventType.OnBubbleUpdated, (eventData: IBubble) => {
      if (conversation.isBubble && conversation.bubble?.jId === eventData.jId) {
        setConversationState({ ...conversationState, name: eventData.name, imageURL: eventData.imageURL });

      }

    });

    return () => {
      presenceUpdated.remove();
      onBubbleUpdated.remove();
    }
  }, [conversation, conversationState]);

  const createActionHandler = () => {
    if (onClickItem) {
      onClickItem(conversation);
    }
  }
  return (
    <View style={styles.container}>
    <TouchableRipple onPress={createActionHandler} style={styles.pressable}>
      <View style={styles.row}>
        <View style={styles.leftSection}>
        <AvatarPresenceBadge peer={conversation} presence={conversationState.contact ? contactPresence : undefined} />
          {conversation.nbMessages > 0 && (
            <Badge style={styles.unreadBadge}>{conversation.nbMessages}</Badge>
          )}
          <View style={styles.textContainer}>
            <Text style={styles.nameText}>{conversation.name}</Text>
            {showLiveMessage ? (
              <Text style={styles.liveButtonText} >{Strings.Live}</Text>
            ) : (
              <Text style={styles.messagePreview}>
                {conversation.lastMsg ? conversation.lastMsg.split('\n')[0].slice(0, 30) + ' ...' : ''}
              </Text>
            )}
          </View>
        </View>
        {conversation.date && (
          <Text style={styles.dateText}>
            {moment(conversation.date, 'ddd MMM DD HH:mm:ss YYYY').format('MMM DD, YYYY')}

          </Text>
        )}
      </View>
    </TouchableRipple>
    <Divider style={styles.divider} />
  </View>
  );
}

const styles =  StyleSheet.create({
  container: {
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  pressable: {
    overflow: 'hidden',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  leftSection: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  textContainer: {
    marginLeft: 16,
  },
  unreadBadge: {
    backgroundColor: '#D32F2F',
    color: 'white',
    fontSize: 10,
    position: 'absolute',
    left: 36,
    top: -4,
  },
  nameText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  liveButton: {
    backgroundColor: '#D32F2F',
    paddingHorizontal: 5,
  },
  liveButtonText: {
    color: 'white',
    fontSize: 12,
  },
  messagePreview: {
    fontSize: 14,
    color: 'gray',
  },
  dateText: {
    fontSize: 12,
    color: 'gray',
  },
  divider: {
    marginTop: 8,
    backgroundColor: 'lightgray',
    height: 1,
  },
});