import React, {useCallback, useEffect, useMemo} from 'react';
import {
  Keyboard,
  Pressable,
  SectionList,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import {useTranslation} from 'react-i18next';
import {InputSearch, Spinner, Typography} from '@components';
import {useAvoidLinkingUrlNavigation} from '@hooks/useAvoidLinkingNavigation';
import {SECTION_LABEL} from '@modules/universalSearch/constants';
import {useTheme} from '@shared/theme';
import {logAmplitudeEvent} from '@shared/utils';
import {AMPLITUDE_EVENTS, DEFAULT_THRESHOLD} from '@shared/constants';

import {UniversalSearchModule, UniversalSearchResult} from '../../interfaces';
import {useUniversalSearch} from '../../hooks/useUniversalSearch';
import {FilterChips} from './components/FilterChips';
import {RecentSearches} from './components/RecentSearches';
import {SearchEmptyState} from './components/SearchEmptyState';
import {SearchResultItem} from './components/SearchResultItem';
import {SearchResultSkeleton} from './components/SearchResultSkeleton';
import {styles} from './styles';
import {buildSections} from './utils';

const keyExtractor = (item: UniversalSearchResult) => item.id;

const UNIVERSAL_SEARCH_MODULE = 'universal search';

function UniversalSearch() {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {
    query,
    setQuery,
    selectedModule,
    setSelectedModule,
    availableModules,
    debouncedQuery,
    data,
    isLoading,
    isFetchingNextPage,
    getNextPage,
    history,
    clearHistory,
  } = useUniversalSearch();
  const {onUrlPress} = useAvoidLinkingUrlNavigation();

  const sections = useMemo(
    () => buildSections(data, selectedModule),
    [data, selectedModule],
  );

  const showSkeleton = isLoading && !data.length;
  const showEmptyState = !isLoading && !!debouncedQuery.length && !data.length;
  const showRecentSearches =
    !debouncedQuery.length && !isLoading && !!history.length;
  const showInitialEmptyState =
    !debouncedQuery.length && !isLoading && !history.length;

  useEffect(() => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.SEARCH_OPENED, {
      module: UNIVERSAL_SEARCH_MODULE,
    });
  }, []);

  useEffect(() => {
    if (debouncedQuery.length) {
      logAmplitudeEvent(AMPLITUDE_EVENTS.SEARCH_PERFORMED, {
        module: UNIVERSAL_SEARCH_MODULE,
        query: debouncedQuery,
      });
    }
  }, [debouncedQuery]);

  const onResultPress = useCallback(
    (result: UniversalSearchResult) => {
      logAmplitudeEvent(AMPLITUDE_EVENTS.SEARCH_RESULT_CLICKED, {
        module: UNIVERSAL_SEARCH_MODULE,
      });
      if (result.path) {
        onUrlPress(result.path);
      }
    },
    [onUrlPress],
  );

  const renderItem = useCallback(
    ({item}: {item: UniversalSearchResult}) => (
      <Pressable disabled={!item.path} onPress={() => onResultPress(item)}>
        <SearchResultItem result={item} highlight={debouncedQuery} />
      </Pressable>
    ),
    [debouncedQuery, onResultPress],
  );

  const renderSectionHeader = useCallback(
    ({
      section,
    }: {
      section: {
        module: UniversalSearchModule;
        data: UniversalSearchResult[];
      };
    }) => (
      <Typography
        variant="s"
        color={theme.text.neutral.lighter}
        style={styles.sectionHeader}>
        {t(SECTION_LABEL[section.module])}
      </Typography>
    ),
    [t, theme.text.neutral.lighter],
  );

  return (
    <View
      style={[
        styles.container,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View>
          <View style={styles.searchInputContainer}>
            <InputSearch
              value={query}
              onChangeText={setQuery}
              placeholder={t('global_search.placeholder')}
              variant="secondary"
              autoFocus
            />
          </View>

          {!!(debouncedQuery.length && availableModules.length) && (
            <FilterChips
              selectedModule={selectedModule}
              availableModules={availableModules}
              onSelect={setSelectedModule}
            />
          )}
        </View>
      </TouchableWithoutFeedback>

      {showSkeleton && <SearchResultSkeleton />}

      {showRecentSearches && (
        <RecentSearches
          history={history}
          onSelect={setQuery}
          onClear={clearHistory}
        />
      )}

      {(showEmptyState || showInitialEmptyState) && (
        <SearchEmptyState isInitial={showInitialEmptyState} />
      )}

      {!showSkeleton && !!sections.length && (
        <SectionList
          style={styles.list}
          sections={sections}
          keyExtractor={keyExtractor}
          renderItem={renderItem}
          renderSectionHeader={renderSectionHeader}
          stickySectionHeadersEnabled={false}
          contentContainerStyle={styles.listContent}
          keyboardDismissMode="on-drag"
          onEndReached={getNextPage}
          onEndReachedThreshold={DEFAULT_THRESHOLD}
          showsVerticalScrollIndicator={false}
          ListFooterComponent={
            isFetchingNextPage ? (
              <View style={styles.footer}>
                <Spinner />
              </View>
            ) : null
          }
        />
      )}
    </View>
  );
}

export default UniversalSearch;
