import { TextInput, ScrollView, Dimensions, StyleSheet, useWindowDimensions, Alert, } from 'react-native';
import React, { useContext, useEffect, } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import UserAvatar from 'react-native-user-avatar';
import { ThemeContext } from 'styled-components';
import { Button, Flex, VStack, Text, Box, Tooltip, HStack, CheckBox, } from '../../themes/components';
import { MediaRoomContext } from '../../services/MediaRoomService';
import { PeersServiceContext } from '../../services/PeersService';
import { MessageTypes, } from '../../types/APITypes';
import { markMessagesRead } from '../../store/roomSlice';
import { useDisclosure } from '../../utils/browser-utils';
import borderRadius from '../../themes/foundations/borderRadius';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
const styles = StyleSheet.create({
    createPollInputText: {
        paddingLeft: 15,
        paddingRight: 5,
        marginTop: 20,
        borderRadius: borderRadius.medium,
        paddingTop: 10,
        paddingBottom: 10,
    },
});
function CreateNewPoll(props) {
    const { toggle } = props;
    const { mediaRoom } = useContext(MediaRoomContext);
    const [pollData, setPollData] = React.useState({
        question: '',
        options: Array(2).fill(''),
        anonymous: false,
        hideVotes: true,
    });
    const { colors } = useContext(ThemeContext);
    const createPoll = () => {
        const { question, options } = pollData;
        if (!question) {
            Alert.alert('Error:', 'Question Can\'t be empty', [
                { text: 'OK' },
            ]);
        }
        else if ((options[0] === '' || options[1] === '')) {
            Alert.alert('Error:', 'Please add minimum two options', [
                { text: 'OK' },
            ]);
        }
        else {
            const data = { ...pollData };
            data.options = options.filter((el) => el !== '');
            mediaRoom.newPoll(data);
            toggle();
        }
    };
    const onQuestionTextChange = (question) => {
        setPollData({ ...pollData, question });
    };
    const onChangeOptionsText = (text, index) => {
        const { options } = pollData;
        options[index] = text;
        setPollData({ ...pollData, options });
    };
    const addOption = () => {
        const { options } = pollData;
        options.push('');
        setPollData({ ...pollData, options });
    };
    const onChangeAnonymous = () => {
        const anonymous = !pollData.anonymous;
        setPollData({ ...pollData, anonymous });
    };
    const hideResultsBeforeVoting = () => {
        const hideVotes = !pollData.hideVotes;
        setPollData({ ...pollData, hideVotes });
    };
    return (<ScrollView>
			<Box py={20} px={10}>
				<VStack spacing={4}>
					<Text fontSize="xl" textAlign="center">Poll Question</Text>
					<TextInput multiline autoFocus={false} placeholder="What is your poll for?" numberOfLines={4} value={pollData.question} placeholderTextColor={colors.textPrimary['400']} onChangeText={onQuestionTextChange} style={[{
            backgroundColor: colors.secondary['800'],
            height: 75,
            color: colors.textPrimary[300],
        }, styles.createPollInputText]}/>
					{(pollData.options.map((poll, index) => (<TextInput key={`pollOptions${index}`} autoFocus={false} placeholder="Enter an option" value={pollData.options[index]} placeholderTextColor={colors.textPrimary['400']} onChangeText={(text) => onChangeOptionsText(text, index)} style={[{
            backgroundColor: colors.secondary['800'],
            color: colors.textPrimary[300],
        }, styles.createPollInputText]}/>)))}
					<Box bg="secondary.700" mt={20} width={125} height={30} alignItems="center" justifyContent="center">
						<Button onClick={() => addOption()}>
							<Text>+ Add an Option</Text>
						</Button>
					</Box>
					<CheckBox rightText="Anonymous" style={{
        marginTop: 15, paddingRight: 10, height: 20, justifyContent: 'center', borderRadius: borderRadius.small,
    }} rightTextStyle={{ color: 'white' }} checkedCheckBoxColor="white" uncheckedCheckBoxColor="white" isChecked={pollData.anonymous} onClick={onChangeAnonymous}/>
					<CheckBox rightText="Hide Results before Voting" style={{
        marginTop: 15, paddingRight: 10, height: 20, justifyContent: 'center', borderRadius: borderRadius.small,
    }} rightTextStyle={{ color: 'white' }} checkedCheckBoxColor="white" uncheckedCheckBoxColor="white" isChecked={pollData.hideVotes} onClick={hideResultsBeforeVoting}/>
					<Box mt={10} bg="primary.500" p={8} mb={5} justify="center" borderRadius={borderRadius.small}>
						<Button fontSize="16" onClick={createPoll}>
							<Text textAlign="center">Create Poll</Text>
						</Button>
					</Box>
				</VStack>
			</Box>
		</ScrollView>);
}
function PollOptionView({ option, index, active, selfId, onChange, }) {
    const { colors } = useContext(ThemeContext);
    const selfVote = option.votes.find((v) => v.id === selfId);
    return (<Box bg={selfVote ? 'primary.500' : 'secondary.700'} borderRadius={borderRadius.medium} p={6} className="dyte-client-noSelect">
			<HStack px={1} align="center" mr={6}>
				<CheckBox style={{
        paddingRight: 10, height: 30, justifyContent: 'center', borderRadius: borderRadius.small,
    }} checkedCheckBoxColor="white" uncheckedCheckBoxColor="white" isChecked={!!selfVote} onClick={onChange}/>
				<Text textAlign="center">{option.text}</Text>
				{option.count !== null && <Text>{`(${option.count})`}</Text>}
			</HStack>
			<HStack mt={1}>
				{option.votes.map((vote, index) => (<Tooltip key={`pollOption${index}`} label={vote.name}>
						<UserAvatar style={{ marginRight: 5, marginTop: 5, marginBottom: 5 }} bgColor={selfVote ? colors.secondary['700'] : colors.primary['500']} color={colors.textPrimary['100']} name={vote.name}/>
					</Tooltip>))}
			</HStack>
		</Box>);
}
export function PollsCard(props) {
    const { selfPeer, mediaRoom, poll } = props;
    const votePoll = (index) => {
        try {
            mediaRoom.votePoll({
                index,
                pollId: poll.id,
            });
        }
        catch (error) {
            Alert.alert('Error', 'Error: Problem casting your vote', [
                { text: 'OK' },
            ]);
        }
    };
    if (poll) {
        const { id } = poll;
        const maxVotes = Math.max(...poll.options.map((p) => p.votes.length), 0);
        return (<VStack spacing={2} direction="row" bg="secondary.800" p={12} mt={8} borderRadius={borderRadius.medium}>
				<Text textAlign="left">{poll.question}</Text>
				<Box mt={8}>
					{poll.options.map((option, index) => (<Flex key={`poll${index}${id}`} onClick={() => votePoll(index)} mb={4}>
							<PollOptionView active={option.votes.length === maxVotes && option.votes.length > 0} option={option} index={index} selfId={selfPeer.userId} onChange={() => votePoll(index)}/>
						</Flex>))}
				</Box>
			</VStack>);
    }
    return (<Text fontStyle="italic">Poll wasn&apos;t found or has been deleted</Text>);
}
export default function PollsTab() {
    const { sessionConfig } = useContext(ConfigServiceContext);
    const pollsCreationAllowed = sessionConfig.permissions.polls.can_create;
    const { isOpen, onClose, onOpen } = useDisclosure();
    const { mediaRoom } = useContext(MediaRoomContext);
    const { selfPeer } = useContext(PeersServiceContext);
    const polls = useSelector((state) => state.room.polls);
    const windowDimensions = useWindowDimensions();
    const { height } = sessionConfig.theme.dimensions || windowDimensions;
    const drawerHeight = Math.floor(height * 2 / 3);
    const onToggle = () => {
        isOpen ? onClose() : onOpen();
    };
    const chatMessages = useSelector((state) => state.room.chatMessages);
    const unread = chatMessages.filter((m) => m.read !== true && m.type === MessageTypes.poll);
    const dispatch = useDispatch();
    useEffect(() => {
        if (unread.length > 0) {
            dispatch(markMessagesRead({ [MessageTypes.poll]: true }));
        }
    }, [unread]);
    return (<Flex height={height} direction="column" justifyContent="space-between" overflowY="auto" px={10} pb={20} pt={100}>
			<Flex>
				<Box overflowY="auto" className="dyte-client-noScrollbar">

					{!isOpen
        ? (<ScrollView style={{
            height: pollsCreationAllowed ? Dimensions.get('window').height - 180 : Dimensions.get('window').height,
        }}>
								{Object.values(polls).map((poll, index) => (<Box key={`pollsTab${index}`} my={10}>
										<Text ml={4}>
											{poll.createdBy ? `Poll by ${poll.createdBy}` : ''}
										</Text>
										<Box mt={1} className="dyte-client-bubble dyte-client-other dyte-client-type-3">
											<PollsCard mediaRoom={mediaRoom} poll={poll} selfPeer={selfPeer}/>
										</Box>
									</Box>))}
							</ScrollView>)
        : <Box>{isOpen && <CreateNewPoll toggle={onToggle}/>}</Box>}
				</Box>
			</Flex>
			{pollsCreationAllowed &&
        <Button fontSize="16" onClick={onToggle}>
				<Box bg={isOpen ? 'danger.500' : 'primary.500'} p={8} mb={5} justify="center" borderRadius={borderRadius.small}>
					<Text textAlign="center">{isOpen ? 'Cancel Poll Creation' : 'Create New Poll'}</Text>
				</Box>
			</Button>}
		</Flex>);
}
//# sourceMappingURL=PollsTab.js.map