
import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Dimensions,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  createBubble,
  createBubbleWithParticipants,
} from '../../store/bubbles/bubblesSlice';
import { BubbleErrorCode } from '../../store/bubbles/types';
import { Logger } from '../../utils/Log';
import { ParticipantsListView } from '../common/ParticipantsListView';
import { Header } from '../common/Header';
import Icon from 'react-native-vector-icons/Ionicons';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { Badge, Button, TextInput } from 'react-native-paper';
interface IProps {
  onBubbleCreationResult: (creationResult: BubbleErrorCode) => void;
}
export const CreateBubble: React.FunctionComponent<IProps> = ({
  onBubbleCreationResult,
}) => {
  const logger = new Logger('CreateBubbleComponent');
  const [bubbleName, setBubbleName] = useState('');
  const [bubbleTopic, setBubbleTopic] = useState('');
  const [validBubbleName, setValidBubbleName] = useState(false);
  const [participantsID, setParticipantsID] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedTab, setSelectedTab] = React.useState<number>(1);
  const dispatch = useAppDispatch();
  const rosters = useAppSelector((state) => state.contacts.contacts);
  useEffect(() => {
    const createBubbleListener = eventEmitter.addListener(
      EventType.CreateBubbleResult,
      (creationResult: BubbleErrorCode) => {
        logger.info(`CreateBubbleResult event trigger with result: ${creationResult}`);
        setLoading(false);
        onBubbleCreationResult(creationResult);
      }
    );
    const addParticipantListener = eventEmitter.addListener(
      EventType.AddParticipantResult,
      (addParticipantResult: BubbleErrorCode) => {
        logger.info(`AddParticipantResult event trigger with result: ${addParticipantResult}`);
        setLoading(false);
        onBubbleCreationResult(addParticipantResult);
      }
    );

    return () => {
      createBubbleListener.remove();
      addParticipantListener.remove();
    }
  }, [validBubbleName]);

  const onBubbleNameChange = (name: string) => {
    setBubbleName(name);
    if (name.length < 3 || name.length === 0) {
      setValidBubbleName(false);
    } else {
      setValidBubbleName(true);
    }
  };
  const onBubbleTopicChange = (topic: string) => {
    setBubbleTopic(topic);
  };
  const updateParticipants = (selectedParticipantsID: string[]) => {
    setParticipantsID(selectedParticipantsID);
  };
  const onClickCreateBubble = () => {
    setLoading(true);
    if (participantsID != null && participantsID.length !== 0) {
      dispatch(createBubbleWithParticipants({ name: bubbleName, topic: bubbleTopic, participantsId: participantsID }))
    } else {
      dispatch(createBubble({ name: bubbleName, topic: bubbleTopic }));
    }
  };

  const infoTab = () => {
    return (
      <View style={styles.container}>
        <TextInput
          mode="outlined"
          placeholder="Enter name"
          style={styles.input}
          onChangeText={onBubbleNameChange}
          error={!validBubbleName}
        />
        {!validBubbleName && (
          <View style={styles.warningContainer}>
            <Badge style={styles.warningBadge}>!</Badge>
            <Text style={styles.errorText}>{Strings.bubbleNameException}</Text>
          </View>
        )}
        <TextInput
          mode="outlined"
          placeholder={Strings.bubbleTopic}
          style={styles.input}
          onChangeText={onBubbleTopicChange}
        />
      </View>
    );
  }

  const renderCenterHeader = () => {
    return <Text style={styles.headerText}>{Strings.createBubble}</Text>;
  }
  const renderRightHeader = () => {
    return validBubbleName && <Icon name="checkmark" size={50} color="#0086CF" onPress={onClickCreateBubble} />
  }

  const renderTab = () => {
    switch (selectedTab) {
      case 1:
        return infoTab();
      case 2:
        return <ParticipantsListView participants={rosters} onParticipantsUpdated={updateParticipants} />
      default:
        return null
    }
  }
  return (
    <>
      <Header centerComponent={renderCenterHeader} rightComponent={renderRightHeader} />
      <View style={styles.tabContainer}>
        <Button
          mode={selectedTab === 1 ? "contained" : "outlined"}
          onPress={setSelectedTab(1)}
          style={styles.tabButton}
        >
          {Strings.bubbleInfo}
        </Button>
        <Button
          mode={selectedTab === 2 ? "contained" : "outlined"}
          onPress={setSelectedTab(2)}
          style={styles.tabButton}
        >
          {Strings.participants}
        </Button>
      </View>
      {renderTab()}
      {loading && (
        <View style={styles.loader}>
          <ActivityIndicator color="#0086CF" size="large" />
        </View>
      )}

    </>
  )
}

const styles = StyleSheet.create({
  loader: {
    flex: 1,
    justifyContent: 'center',
    opacity: 1,
    position: 'absolute',
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
    backgroundColor: 'rgba(234, 236, 238, 0.8)',
  },
  container: {
    padding: 20,
    justifyContent: 'space-around',
  },
  input: {
    marginBottom: 10,
  },
  warningContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  warningBadge: {
    backgroundColor: 'red',
    marginRight: 5,
  },
  errorText: {
    color: 'red',
    fontSize: 12,
  },
  appbar: {
    backgroundColor: '#57b9ff',
  },
  tabContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginVertical: 10,
  },
  tabButton: {
    flex: 1,
    marginHorizontal: 5,
  },
  headerText: {
    textAlign: 'center',
    alignSelf: 'center',
    fontSize: 16,
    color: '#0086CF',

  }
});