import React, { FunctionComponent, useEffect, useState } from 'react';
import {
  StyleSheet,
  Text,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { IStyledProps } from '../common/types';
import { IConversation } from '../../store/conversations/types';
import { ParticipantsListView } from '../common/ParticipantsListView';
import { getConversations, getConversationsResult } from '../../store/conversations/conversationSlice';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { Header } from '../common/Header';
import { ForwardedViewNavigationProp, ForwardedViewRouteProp } from '../../RootStackParamList';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { forwardMessage } from '../../store/messages/messagesSlice';
import { TextInput } from 'react-native-paper';
interface IForwardingActionsProps extends IStyledProps<IForwardingStyleProps> {
  navigation: ForwardedViewNavigationProp;
  route: ForwardedViewRouteProp
  customView?: React.ReactNode,
}
interface IForwardingStyleProps {
  forwardingBody?: ViewStyle;
  headerTitle?: TextStyle;
  errorText?: TextStyle;
  forwardActiveButton?: ViewStyle;
  forwardInActiveButton?: ViewStyle;
  msgView?: ViewStyle;
  forwardText?: TextStyle
  messageTabStyle?: ViewStyle;
  participantsTabStyle?: ViewStyle;
  container?: ViewStyle;
  tabText?: ViewStyle;
  tab?: ViewStyle;
  input?: ViewStyle;
}
const MessageForwardedView: FunctionComponent<IForwardingActionsProps> = ({
  customView,
  style,
  route,
  navigation
}) => {
  const selectedMessage = route.params.message;
  const mergedStyle = { ...defaultStyle, ...style };
  const [msgText, setMsgText] = useState('');
  const [ConversationsID, setConversationsID] = useState<string[]>([]);
  const [selectedTab, setSelectedTab] = React.useState<number>(1);
  const dispatch = useAppDispatch();
  const conversations = useAppSelector((state) => state.conversations.conversations);

  useEffect(() => {
    getConversations();
    eventEmitter.addListener(
      EventType.ConversationsUpdated,
      (eventData: IConversation[]) => {
        dispatch(getConversationsResult(eventData));
      }
    );
  }, [getConversations, getConversationsResult]);

  const onTextChange = (name: string) => {
    setMsgText(name);
  };

  const updateConversations = (selectedConversationsID: string[]) => {
    setConversationsID(selectedConversationsID);
  };


  const onForwardingClick = () => {
    dispatch(forwardMessage({ text: msgText, message: selectedMessage, conversationsIds: ConversationsID }))
    navigation.pop();
  }
  const renderForwardingBody = () => {
    return (
      <View style={mergedStyle.forwardingBody}>
        <TextInput
          mode="outlined"
          keyboardType="default"
          placeholder="Write your message here"
          value={msgText}
          onChangeText={onTextChange}
          style={mergedStyle.input}
          outlineColor="black"
          theme={{ colors: { primary: 'black' } }}
        />
        <View style={mergedStyle.msgView}>
          <Text>{selectedMessage.text}</Text>
        </View>

        {ConversationsID.length === 0 && <Text style={mergedStyle.errorText}>{Strings.forwardError}</Text>}
        <TouchableOpacity disabled={ConversationsID.length > 0 ? false : true} style={ConversationsID.length > 0 ? mergedStyle.forwardActiveButton : mergedStyle.forwardInActiveButton} onPress={onForwardingClick}>
          <Text style={mergedStyle.forwardText}>
            {Strings.forward}
          </Text>
        </TouchableOpacity>
      </View>
    );
  };
  const renderCenterHeader = () => {
    return <Text style={mergedStyle.headerTitle} >{'Forwarding Message'}</Text>

  }
  const renderTab = () => {
    switch (selectedTab) {
      case 1:
        return renderForwardingBody()
      case 2:
        return <ParticipantsListView participants={conversations} onParticipantsUpdated={updateConversations} />
      default:
        return null
    }
  }
  if (customView) {
    return <>{customView}</>
  } else {
    return (
      <>
        <Header centerComponent={renderCenterHeader} />
        <View style={mergedStyle.container}>
          <TouchableOpacity
            style={[
              mergedStyle.tab,
              { backgroundColor: selectedTab === 1 ? 'gray' : '#57b9ff' }
            ]}
            onPress={() => setSelectedTab(1)}
          >
            <Text style={mergedStyle.tabText}>Message</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              mergedStyle.tab,
              { backgroundColor: selectedTab === 2 ? 'gary' : '#57b9ff' }
            ]}
            onPress={() => setSelectedTab(2)}
          >
            <Text style={mergedStyle.tabText}>Conversations</Text>
          </TouchableOpacity>
        </View>
        {renderTab()}
      </>
    );
  }

};

export const ForwardedView = MessageForwardedView;

const defaultStyle: IForwardingStyleProps = StyleSheet.create({
  errorText: {
    color: 'red',
    fontSize: 14,
    margin: 10
  },
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    height: 'auto',
  },
  headerTitle: {
    textAlign: 'center',
    alignSelf: 'center',
    color: '#ffffff',
    fontSize: 16
  },
  forwardingBody: {
    flexDirection: 'column',
    flex: 1,
    paddingStart: 10,
    paddingEnd: 10,
    paddingTop: 20
  },
  forwardActiveButton: {
    alignSelf: 'stretch', height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: '#3786c9'
  },
  forwardInActiveButton: {
    alignSelf: 'stretch', height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: '#8bb8df'
  },
  msgView: {
    height: 200, backgroundColor: '#f2f2f2', marginTop: 10, marginBottom: 20, padding: 10
  },
  forwardText: {
    color: 'white'
  },
  input: {
    marginTop: 20,
  },
});

