
import React, { useEffect, useState } from 'react';
import { View, Modal, StyleSheet, ImageStyle, Pressable } from 'react-native';
import { Text} from 'react-native-paper';
import { Presence } from '../../store/contacts/types';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { Logger } from '../../utils/Log';
import { IUser } from '../../store/userProfile/types';
import { Strings } from '../../resources/localization/Strings'
import { PresenceView as PresenceIcon } from './PresenceView';
import { useAppDispatch } from '../../store/hooks';
import { getGetConnectedUser, setPresence } from '../../store/auth/authSlice';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';


const logger = new Logger('UserPresenceList');
export interface IPresenceListProps {
	presenceIconSize?: number;
	presenceItemView?: () => React.ReactNode;
	modalTitle?: string;
}

export const PresenceList: React.FunctionComponent<IPresenceListProps> = ({
	presenceIconSize,
	presenceItemView

}) => {
	const [connectedUser, setConnectedUser] = useState<IUser>();
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const [connectedUserPresence, setConnectedUserPresence] = useState<Presence>(connectedUser?.contact?.presence ?? Presence.offline);
	const presencesOptions = [Presence.online, Presence.away, Presence.offline, Presence.DoNotDisturb];
	const dispatch = useAppDispatch();

	useEffect(() => {
		dispatch(getGetConnectedUser())
		const connectedUserUpdated = eventEmitter.addListener(
			EventType.ConnectedUserUpdated,
			(eventData: IUser) => {
				logger.info(`ConnectedUserUpdated${eventData}`);
				if (eventData) {
					setConnectedUser(eventData);
					setConnectedUserPresence(eventData.contact?.presence)
				}
			}
		);
		const connectedUserPresenceUpdatedEvent = eventEmitter.addListener(
			EventType.ConnectedUserPresenceUpdated,
			(eventData: { presence: Presence; contactJId: string }) => {
				logger.info(`connectedUserPresenceUpdatedEvent: ${eventData}`);
				setConnectedUserPresence(eventData.presence);
			}
		)
		return () => {
			connectedUserUpdated.remove();
			connectedUserPresenceUpdatedEvent.remove();
		}

	}, []);

	const showModalView = () => {
		setModalVisible(true);
	}

	const hideModalView = () => {
		setModalVisible(false);
	}
	const defaultPresenceItemView = (presence: Presence, onPress: () => void, customRightItem?: React.ReactNode) => {
		return (
			<Pressable onPress={onPress} key={presence} style={defaultStyle.itemContainer}>

					<PresenceIcon presence={presence} size={presenceIconSize} />


					<Text style={{marginLeft: 15}} >
						{Strings.presenceOption[presence]}
					</Text>


					{customRightItem && (
						<View style={defaultStyle.rightItemContainer}>
							{customRightItem}
						</View>
					)}

			</Pressable>
		);
	};

	const renderPresenceItemView = () => {
		if (presenceItemView) {
			return presenceItemView();
		}
		else {
			return defaultPresenceItemView(connectedUserPresence, showModalView, <MaterialCommunityIcons name="check" size={20} color="#0086CF" />)
		}

	}
	const handleChangePresence = (presence: Presence) => () => {
		dispatch(setPresence(presence));
	};

	if (!connectedUser?.contact) return null;
	return (
		<>
			{renderPresenceItemView()}
			<Modal
				animationType="slide"
				transparent={true}
				visible={modalVisible}
				onRequestClose={hideModalView}>
				<Pressable style={defaultStyle.centeredView} onPressOut={hideModalView}>
					<View style={defaultStyle.modalView}>
						<Text style={defaultStyle.modalTitleText}>{Strings.presence}</Text>
						{
							presencesOptions.map((item: Presence) => {
								const leftIcon = (connectedUserPresence === item || (connectedUserPresence === Presence.mobile_online && item === Presence.online)) && <MaterialCommunityIcons name="check" size={20} color="#0086CF" />
								return defaultPresenceItemView(item, handleChangePresence(item), leftIcon);
							})
						}
					</View>
				</Pressable>
			</Modal>
		</>
	);
};

const defaultStyle = StyleSheet.create(
	{
		centeredView: {
			flex: 1,
			justifyContent: 'center',
			alignItems: 'center',
		},
		modalView: {
			width: '70%',
			margin: 20,
			backgroundColor: 'white',
			borderRadius: 10,
			padding: 20,
			shadowColor: '#000',
			shadowOffset: {
				width: 0,
				height: 2
			},
			shadowOpacity: 0.25,
			shadowRadius: 4,
			elevation: 5,
			marginLeft: 30,
			marginRight: 30

		},
		modalTitleText: {
			textAlign: 'center',
			fontSize: 22,
			color: '#3B3B3B',
			margin: 10
		},
		BodyContainer: {
			marginLeft: 20
		},
		itemContainer: {
			paddingVertical: 10,
			paddingHorizontal: 15,
			flexDirection: 'row',
			alignItems: 'center',
			width: '100%',			
		},
		titleText: {
			flex: 1,
			fontSize: 16,
			color: '#333',
		},
		rightItemContainer: {
			flex: 1,
			alignItems: 'flex-end'
		}
	}
);
