import React, {useCallback, useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import * as Sentry from '@sentry/react-native';
import {Button, CloseButton, InputSearch, Title, Typography} from '@components';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {Navigation} from '@interfaces/navigation';
import {ChatSearchUsers} from '@modules/chats/components';
import {ChatUser} from '@modules/chats/interfaces';
import {useNewChatMembers} from '@modules/chats/store/zustand/useNewChatSharedData';
import {useTheme} from '@shared/theme';
import {Screens} from '@shared/constants';

import {styles} from './styles';

function ChatNewScreenComponent({
  navigation,
  route,
}: Navigation<Screens.CHATS_NEW | Screens.CHATS_NEW_GROUP>) {
  const [selectedUsers, setSelectedUsers] = useState<ChatUser[]>([]);
  const {
    setMembers: setMembersFromSharedData,
    clear,
    members,
  } = useNewChatMembers();
  const bottomSafePadding = useSafeAreaBottomPadding();
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {top} = useSafeAreaInsets();
  const [searchText, setSearchText] = useState('');
  const isGroupCreation = !!route.params?.isGroupCreation;

  useEffect(() => {
    setSelectedUsers(members);
  }, [members, setSelectedUsers]);

  useEffect(() => {
    return () => {
      clear();
    };
  }, [clear]);

  const handleNext = () => {
    setMembersFromSharedData(selectedUsers);
    navigation.navigate(Screens.CHATS_NEW_GROUP_NAME, {users: selectedUsers});
  };

  const onChangeSearchText = useCallback((text: string) => {
    setSearchText(text);
  }, []);

  return (
    <View
      style={[
        styles.container,
        !!top && {paddingTop: top},
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <View
        style={[styles.header, {borderColor: theme.border.neutral.default}]}>
        <Title
          title={t(
            isGroupCreation
              ? 'chat.groups.create.add_members'
              : 'chat.new_chat',
          )}
          center
        />
        {isGroupCreation && (
          <Typography
            align="center"
            variant="xxs"
            color={theme.text.neutral.lighter}>
            {t('chat.groups.create.select_members', {
              count: selectedUsers.length,
            })}
          </Typography>
        )}
        <View style={styles.backButtonContainer}>
          <CloseButton onPress={navigation.popToTop} />
        </View>
      </View>
      <View
        style={[
          styles.inputSearchContainer,
          {borderColor: theme.border.neutral.default},
        ]}>
        <InputSearch
          value={searchText}
          onChangeText={onChangeSearchText}
          placeholder={t('general.search')}
          autoCorrect={false}
          variant="custom"
        />
      </View>
      <View
        style={[
          styles.content,
          {backgroundColor: theme.background.layout.default},
        ]}>
        <ChatSearchUsers
          searchText={searchText}
          selectEnabled={isGroupCreation}
          topButtons={!isGroupCreation ? ['group'] : []}
          selectedUsers={selectedUsers}
          setSelectedUsers={setSelectedUsers}
          // Hide keyboard when dragging the list
          keyboardDismissMode={'on-drag'}
          // Allow selecting users while keyboard is open
          keyboardShouldPersistTaps={'handled'}
          backgroundColor={theme.background.layout.default}
        />
        {isGroupCreation && (
          <View
            style={[
              {
                paddingBottom: bottomSafePadding,
                backgroundColor: theme.background.layout.tertiary,
                borderColor: theme.border.neutral.default,
              },
              styles.nextButtonContainer,
            ]}>
            <Button text={t('general.next')} onPress={handleNext} />
          </View>
        )}
      </View>
    </View>
  );
}

export const ChatNewScreen = Sentry.withProfiler(ChatNewScreenComponent, {
  name: 'Chats2.ChatNewScreen',
}) as typeof ChatNewScreenComponent;
