import React, { useEffect } from 'react';
import { Alert, SectionList, SectionListData, Text, View } from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  acceptInvitation,
  cancelInvitation,
  declineInvitation,
  getInvitations,
  getReceivedInvitationsResult,
  sendInvitationByEmail,
  getSentInvitationsResult,
} from '../../store/invitations/invitationsSlice';
import { IInvitation } from '../../store/invitations/types';
import { Logger } from '../../utils/Log';
import { InvitationCardView } from './InvitationCardView';
import { useAppDispatch, useAppSelector } from '../../store/hooks';

/**
 * @module
 * @name Invitations
 * @public
 * @description This module is used to represent an invitation received or sent by/to user.
 */
export const InvitationsContainer: React.FunctionComponent = () => {
  const logger = new Logger('InvitationsContainer');
  const dispatch= useAppDispatch();
  const receivedInvitations = useAppSelector((state) => state.invitations.receivedInvitations);
  const sentInvitations = useAppSelector((state) => state.invitations.sentInvitations);


  useEffect(() => {
    dispatch(getInvitations());
    eventEmitter.addListener(
      EventType.SentInvitationsUpdated,
      (eventData: IInvitation[]) => {
        logger.info(`'sentInvitationsUpdated' ${eventData}`);
        dispatch(getSentInvitationsResult(eventData));
      }
    );
    eventEmitter.addListener(
      EventType.ReceivedInvitationsUpdated,
      (eventData: IInvitation[]) => {
        logger.info(`receivedInvitationsUpdated:  ${eventData}`);
        dispatch(getReceivedInvitationsResult(eventData));
      }
    );

    eventEmitter.addListener(
      EventType.InvitationResponse,
      (eventData: string) => {
        logger.info('InvitationResponse');
        if (eventData) {
          Alert.alert('Invitation Response', eventData);
        }    
        }
    );
  }, []);
  const renderSectionHeader = ({
    section,
  }: {
    section: SectionListData<IInvitation>;
  }) => {
    if (section.data.length > 0) {
      return <Text style={{backgroundColor:"#eeeded", color:"!0086CF", fontSize:16, paddingVertical: 2}}  >{section.title}</Text>;
    }
    return null;
  };

  const InvitationsData = [
    {
      title: Strings.receivedInvitations,
      data: receivedInvitations
    },
    {
      title: Strings.sentInvitation,
      data: sentInvitations
    }
  ]
  const renderItem = ({ item, section }: { item?: IInvitation, section: SectionListData<IInvitation> }) => {
    if (!item) {
      return null;
    }

    if (section.title === Strings.receivedInvitations) {
      return (
        <InvitationCardView
          invitation={item}
          onAccept={(invitation) => dispatch(acceptInvitation(invitation.invitationId))}
          onDecline={(invitation) => dispatch(declineInvitation(invitation.invitationId))}
        />
      );
    }

    if (section.title === Strings.sentInvitation) {
      return (
        <InvitationCardView
          invitation={item}
          onCancel={(invitation) => dispatch(cancelInvitation(invitation.invitationId))}
          onResend={(invitation) => dispatch(sendInvitationByEmail(invitation.invitedUserEmail))}
        />
      );
    }

    return null;
  };
  return (
    InvitationsData.every(section => section.data.length === 0) ? (
      <Text style={{ flex: 1, alignSelf: 'center', justifyContent: 'center'}} >No invitations are available</Text>
    ) : (
      <SectionList
        sections={InvitationsData}
        stickySectionHeadersEnabled={true}
        renderItem={renderItem}
        maxToRenderPerBatch={20}
        windowSize={10}
        renderSectionHeader={renderSectionHeader}
        />
    )
  );
}

