import {useEffect} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconChevronDown, IconChevronUp} from '@tabler/icons-react-native';
import {useShallow} from 'zustand/shallow';
import {IconButton, Typography} from '@components';
import {useMessagesSearch} from '@modules/chats/store';
import {useMessagesListMethodsRef} from '@modules/chats/contexts';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

export function ChatMessagesSearchNavigator() {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const {
    matches,
    currentSelectedMatch,
    query,
    nextMatch,
    prevMatch,
    matchesCountLabel,
    addSearchInitListener,
  } = useMessagesSearch(
    useShallow(state => ({
      matches: state.matches,
      currentSelectedMatch: state.currentSelectedMatch,
      query: state.query,
      nextMatch: state.nextMatch,
      prevMatch: state.prevMatch,
      matchesCountLabel: state.matchesCountLabel,
      addSearchInitListener: state.addSearchInitListener,
    })),
  );
  const isEmptyQuery = query.length === 0;
  const isNextEnabled =
    !isEmptyQuery &&
    currentSelectedMatch &&
    currentSelectedMatch.index < matches.length - 1;
  const isPrevEnabled =
    !isEmptyQuery && currentSelectedMatch && currentSelectedMatch.index > 0;

  const messagesListMethodsRef = useMessagesListMethodsRef();

  useEffect(() => {
    const unsubscribe = addSearchInitListener(currentMatch => {
      if (currentMatch?.ts && messagesListMethodsRef?.current) {
        messagesListMethodsRef?.current?.scrollToMessageByTs(
          currentMatch.ts,
          currentMatch.viewPosition,
        );
      }
    });
    return unsubscribe;
  }, [addSearchInitListener, messagesListMethodsRef]);

  const onNextPress = () => {
    const result = nextMatch();
    if (result && messagesListMethodsRef?.current) {
      messagesListMethodsRef?.current?.scrollToMessageByTs(
        result.ts,
        result.viewPosition,
      );
    }
  };

  const onPrevPress = () => {
    const result = prevMatch();
    if (result && messagesListMethodsRef?.current) {
      messagesListMethodsRef?.current?.scrollToMessageByTs(
        result.ts,
        result.viewPosition,
      );
    }
  };

  return (
    <View
      style={[
        styles.container,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <View style={styles.controls}>
        <IconButton
          variant="flat"
          Icon={IconChevronUp}
          onPress={onNextPress}
          disabled={!isNextEnabled}
          iconColor={
            !isNextEnabled
              ? theme.text.neutral.disabled
              : theme.text.neutral.default
          }
          hitSlop={12}
        />
        <IconButton
          variant="flat"
          Icon={IconChevronDown}
          onPress={onPrevPress}
          disabled={!isPrevEnabled}
          iconColor={
            !isPrevEnabled
              ? theme.text.neutral.disabled
              : theme.text.neutral.default
          }
          hitSlop={12}
        />
      </View>
      {!isEmptyQuery && (
        <Typography
          variant="s"
          color={theme.text.neutral.default}
          align="center"
          style={styles.matchesCountLabel}
          pointerEvents="none">
          {matches.length && currentSelectedMatch
            ? t('chat.search.found_messages_result_n_of', {
                n: currentSelectedMatch.index + 1, // zero-based index
                total: matchesCountLabel, // display 1-99 if > 99 then 99+
                count: Math.min(matches.length, 99), // for pluralization
              })
            : 0}
        </Typography>
      )}
    </View>
  );
}
