import React, { FunctionComponent, useEffect } from 'react';
import { SectionListData, StyleSheet, Text, View } from 'react-native';
import { SectionList } from 'react-native';
import { Logger } from '../../utils/Log';

import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { IContact } from '../../store/contacts/types';
import {
  executeSearch,
  searchFinished,
  getSearchResult
} from '../../store/search/searchSlice';
import { ISearchFilter, SearchType } from '../../store/search/types';
import { ContactItemView } from './ContactItemView';
import { Searching } from './Searching';
import {
  getFilteredDirectoryColleagueContacts,
  getFilteredDirectoryContactsOfOtherCompanies,
  getFilteredEnterpriseContacts,
  getFilteredLocalPhoneContacts,
  getFilteredRosterContacts,
} from './SearchSelector';
import { useAppDispatch, useAppSelector } from '../../store/hooks';

const logger = new Logger('ContactsSearchTabContainer');
interface IProps  {
  onClickItem: (contact: IContact) => void;
}

/**
 * @module
 * @name Search Contact
 * @public
 * @description
 * This module manges handle the Search by name for contacts.
 */
export const ContactsSearchTab: FunctionComponent<IProps> = ({
  onClickItem
}) => {
  const dispatch = useAppDispatch();
  const executingSearch = useAppSelector((state) => state.search.executingSearch);
  const contactsSearchResult = useAppSelector((state) => state.search.contactsSearchResult);
  const searchQuery = useAppSelector((state) => state.search.query);
  
  // Extract all necessary data using useAppSelector at the top
  const rosterContacts = useAppSelector((state) => getFilteredRosterContacts(state));
  const directoryColleagueContacts = useAppSelector((state) => getFilteredDirectoryColleagueContacts(state));
  const enterpriseContacts = useAppSelector((state) => getFilteredEnterpriseContacts(state));
  const localPhoneContacts = useAppSelector((state) => getFilteredLocalPhoneContacts(state));
  const contactsOfOtherCompanies = useAppSelector((state) => getFilteredDirectoryContactsOfOtherCompanies(state));

  useEffect(() => {
    if (searchQuery) {
      logger.info('Executing search ' + searchQuery);
      dispatch(executeSearch({query: searchQuery, searchType: SearchType.Contacts}))
    } else {
      dispatch(getSearchResult([]));
    }

    const contactsSearchEventResult = eventEmitter.addListener(
      EventType.ContactsSearchResult,
      (contacts: IContact[]) => {
        dispatch(getSearchResult(contacts))
      }
    );

    const searchError = eventEmitter.addListener(EventType.SearchError, (errorMessage: string) => {
      logger.info(`search error ${errorMessage}`)
    });

    const onSearchFinished = eventEmitter.addListener(EventType.SearchFinished, () => {
      dispatch(searchFinished());
    });
    return () => {
      contactsSearchEventResult.remove();
      searchError.remove();
      onSearchFinished.remove();
    }
  }, [searchQuery, dispatch]);

  if (executingSearch && (!contactsSearchResult || contactsSearchResult.length === 0)) {
    return <Searching />;
  }

  if (!searchQuery) {
    return null;
  }

  const renderItem = ({ item }: { item: IContact }) => {
    return (
      <ContactItemView
        contact={item}
        onClickItem={onClickItem}
        onCallPress={(contact) => logger.info(`Call ${contact.name}`)}
        onChatPress={(contact) => logger.info(`Chat with ${contact.name}`)}
      />
    );
  };

  const renderSectionHeader = ({
    section,
  }: {
    section: SectionListData<IContact>;
  }) => {
    if (section.data.length > 0) {
      return <Text style={styles.sectionHeader}>{section.title}</Text>;
    }
    return null;
  };

  if (contactsSearchResult.length === 0) {
    return (
      // View to show when list is empty
      <View style={styles.NoDataMessages}>
        <Text style={styles.NoDataMessagesText}>{Strings.noDataFound}</Text>
      </View>
    );
  }
  return (
    <SectionList
      sections={[
        { title: Strings.SearchFilter[ISearchFilter.rosterContact],
           data: rosterContacts },
        { title: Strings.SearchFilter[ISearchFilter.enterpriseContact], data: enterpriseContacts },
        { title: Strings.SearchFilter[ISearchFilter.localPhoneContact], data: localPhoneContacts },
        { title: Strings.SearchFilter[ISearchFilter.directoryColleagueContact], data: directoryColleagueContacts },
        { title: Strings.SearchFilter[ISearchFilter.contactsOfOtherCompanies], data: contactsOfOtherCompanies },
      ]}
      stickySectionHeadersEnabled={true}
      renderItem={renderItem}
      maxToRenderPerBatch={20}
      windowSize={10}
      renderSectionHeader={renderSectionHeader}
    />
  );
};

const styles = StyleSheet.create({
  NoDataMessages: {
    fontSize: 25,
    justifyContent: 'center',
    flex: 1,
    marginTop: 100,
  },
  NoDataMessagesText: {
    textAlign: 'center',
  },
  sectionHeader: {
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 10,
    paddingRight: 10,
    fontSize: 15,
    fontWeight: 'bold',
    color: '#0086CF',
    backgroundColor: '#eeeded',
  },
});
