
import React, { useEffect, useState } from 'react';
import {
  FlatList,
  ImageBackground,
  ImageStyle,
  TextStyle,
  ViewStyle,
  Alert,
  View,
  StyleSheet
} from 'react-native';
import { Platform } from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { contactsService } from '../../services/contacts-service';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  IContact,
  IEmail,
  IPhoneNumber,
  Presence,
} from '../../store/contacts/types';
import { callPBX } from '../../store/pbx/pbxSlice';
import { Logger } from '../../utils/Log';
import { IStyledProps } from '../common/types';
import { removeContact } from '../../store/contacts/contactsSlice';
import { Header } from '../common/Header';
import Icon from 'react-native-vector-icons/Ionicons';
import { AvatarPresenceBadge } from '../presence/AvatarPresenceBadge';
import { ContactInformationNavigationProp, ContactInformationRouteProp } from '../../RootStackParamList';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { CallButton } from '../common/callButton';
import {  Button,Text } from 'react-native-paper';


export interface IProps extends IStyledProps<IContactInfoStyleProps> {
  route: ContactInformationRouteProp;
  navigation: ContactInformationNavigationProp;
}
export interface IContactInfoStyleProps {
  backgroundImg?: ImageStyle;
  itemTextContainer?: TextStyle;
  headerTitle?: TextStyle;
  itemContainer?:ViewStyle;
}
export const ContactInformation: React.FunctionComponent<IProps> = ({
  route,
  style,
}) => {
  const logger = new Logger('ContactInformation');
  const contact = route.params.contact;
  const dispatch = useAppDispatch();
  const user = useAppSelector((state) => state.authReducer.user);

  const { makeCallButtonProps } = route.params;
  const [presence, setPresence] = useState(contact.presence);
  const [updatedContact, setUpdatedContact] = useState(contact);
  const [InvitationSent, setInvitationSent] = useState<boolean>(contact.isInvited);
  const [addRoster, setAddRoster] = useState<boolean>(!updatedContact.isRoster && !updatedContact.isInvited)
  const [removeRoster, setRemoveRoster] = useState<boolean>(updatedContact.isRoster);
  const mergedStyle = { ...styles, ...style };
  useEffect(() => {
    if (
      Platform.OS === 'ios' &&
      !updatedContact.isRoster
       &&
      updatedContact.companyName === user?.contact.companyName
    ) {
      contactsService.fetchContactDetails(updatedContact.jId);
    }
    eventEmitter.addListener(
      EventType.PresenceUpdated,
      (eventData: { presence: Presence; contactJId: string }) => {
        if (eventData.contactJId === updatedContact.jId) {
          logger.info(`onPresenceUpdated : ${updatedContact.name}`);
          setPresence(eventData.presence);
        }
      }
    );
    eventEmitter.addListener(
      EventType.ContactsDetailUpdated,
      (eventData: IContact) => {
        if (eventData.jId === updatedContact.jId) {
          logger.info(`onContactsDetailsUpdated : ${updatedContact.name}`);
          setUpdatedContact(eventData);
        }
      }
    );
    eventEmitter.addListener(
      EventType.RemoveContact,
      (eventData: string) => {
        if (eventData === 'success') {
          logger.info(`removeContact listener`);
          setAddRoster(true);
          setRemoveRoster(false);
        }
      }
    );
    eventEmitter.addListener(
      EventType.AddContactToRoster, (eventData: string) => {
        if (eventData === "success")
          setInvitationSent(true);
        Alert.alert('Invite contact to my network', eventData);
      }
    )
  }, []);
  const renderEmailItem = ({ item }: {item :IEmail}) => {
    return (
      <View style={styles.itemContainer}>
        <Icon name="mail-sharp" size={30} color="#0086CF" />
        <View style={styles.itemTextContainer}>
          <Text style={styles.itemTypeText}>
            {Strings.emailStrings[item.type]}
          </Text>
          <Text>{item.value}</Text>
        </View>
      </View>
    );
  };
  
  const renderPhoneItem = ({ item }: { item: IPhoneNumber }) => {
    return (
      <View style={styles.itemContainer}>
        <Icon name="phone-portrait-sharp" size={30} color="#0086CF" />
        <View style={styles.itemTextContainer}>
          <Text style={styles.itemTypeText}>
            {Strings.phoneStrings[item.type]}
          </Text>
          <Text style={styles.phoneNumberText}>{item.value}</Text>
        </View>
      </View>
    );
  };
  const makeCall = (item: IPhoneNumber) => {
    dispatch(callPBX(item.value));
  };
  const setKeyExtractor = (item: any) => {
    return item.value;
  };
  const removeContactFromNetwork = () => {
    dispatch(removeContact(updatedContact.jId));
  }

  const addToRoster = () => {
    contactsService.addContactToRoster(updatedContact.jId);
  }
  const renderCenterHeader = () => {
    return <Text style={mergedStyle.headerTitle}> {Strings.contactDetails} </Text>;
  }
  const renderRightHeader = () => {
    if (makeCallButtonProps) {
      return <CallButton contact={contact} imageSource={makeCallButtonProps.imageSource} webRtcActions={makeCallButtonProps.webrtcActions} webrtcEnabled={true}/>;

    } else return null;
  }
  return (
    <React.Fragment>
      <Header
        centerComponent={renderCenterHeader}
        rightComponent={renderRightHeader}
      />
         <View style={mergedStyle.container}>
      <ImageBackground
        style={mergedStyle.backgroundImg}
        imageStyle={mergedStyle.imageOpacity}
        source={{ uri: updatedContact.imageURL }}
      >
        <View style={mergedStyle.contactHeader}>
        <AvatarPresenceBadge peer={updatedContact} avatarSize={100} presenceIconSize={20} presence={updatedContact.presence} />
        <View style={styles.contactInfo}>
            <Text variant="titleMedium">{updatedContact.name}</Text>
            <Text variant="bodySmall">{updatedContact.jobTitle}</Text>
            <Text variant="bodySmall">{updatedContact.companyName}</Text>
            <Text variant="bodySmall">{Strings[updatedContact.presence]}</Text>
          </View>
        </View>
      </ImageBackground>


      <View style={styles.actionsContainer}>
        {addToRoster && (
          <Button
            mode="outlined"
            icon={() => <Icon name="person-add" size={20} color="#0086CF" />}
            onPress={addToRoster}
            contentStyle={styles.buttonContent}
            style={styles.rosterButton}
            textColor="#0086CF"
          >
            {Strings.addToMyNetwork}
          </Button>
        )}
        {InvitationSent && (
          <View style={styles.invitationContainer}>
            <Icon name="checkmark-circle" size={20} color="#0086CF" />
            <Text style={styles.invitationText}>{Strings.invitationSent}</Text>
          </View>
        )}
        {removeRoster && (
          <Button
            mode="contained"
            buttonColor="red"
            onPress={removeContactFromNetwork}
            style={styles.removeButton}
          >
            {Strings.removeContact}
          </Button>
        )}
      </View>

      <View style={styles.listsContainer}>
        <FlatList
          data={updatedContact.emails}
          renderItem={renderEmailItem}
          keyExtractor={setKeyExtractor}
        />
        <FlatList
          data={updatedContact.phoneNumbers}
          renderItem={renderPhoneItem}
          keyExtractor={setKeyExtractor}
        />
      </View>
    </View>
    </React.Fragment>



  );
};

const styles = StyleSheet.create({
  text: {
    color: '#FFFFFF',
    fontSize: 12,
  },
  headerTitle: {
    textAlign: 'center',
    alignSelf: 'center',
    fontSize: 16,
    color: '#0086CF',
  },
   itemContainer: {
    flexDirection: 'row',
    padding: 12,
    alignItems: 'center',
  },
  itemTextContainer: {
    marginLeft: 12,
  },
  itemTypeText: {
    color: '#0086CF', // Use a hex code for a consistent color
  },
  phoneNumberText: {
    color: 'black',
  },
  container: {
    flex: 1,
    paddingHorizontal: 16,
  },
  backgroundImg: {
    width: '100%',
    height: 150,
    justifyContent: 'center',
  },
  imageOpacity: {
    opacity: 0.2,
  },
  contactHeader: {
    flexDirection: 'row',
    padding: 16,
    alignItems: 'center',
  },
  contactInfo: {
    marginLeft: 16,
  },
  actionsContainer: {
    padding: 16,
  },
  rosterButton: {
    marginVertical: 8,
  },
  buttonContent: {
    flexDirection: 'row-reverse',
  },
  invitationContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 8,
  },
  invitationText: {
    color: '#0086CF',
    marginLeft: 8,
  },
  removeButton: {
    marginVertical: 8,
  },
  listsContainer: {
    padding: 16,
  }
});
