import React, {useCallback, useMemo, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useMutation} from '@tanstack/react-query';
import {Dialog, InputSearch} from '@components';
import {ChatSearchUsers} from '@modules/chats/components';
import {ChatUser} from '@modules/chats/interfaces';
import {inviteUsersToConversation} from '@modules/chats/services';
import {visibleChatStore} from '@modules/chats/store/zustand/visibleChat';
import {getUlid} from '@shared/utils';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  channel: string;
  isVisible: boolean;
  onClose: () => void;
}

function DialogAddMembers({channel, isVisible, onClose}: Props) {
  const [selectedUsers, setSelectedUsers] = useState<ChatUser[]>([]);
  const [searchText, setSearchText] = useState('');
  const {theme} = useTheme();

  const handleClose = useCallback(() => {
    onClose();
    setSelectedUsers([]);
    setSearchText('');
  }, [onClose]);

  const {mutate, isPending} = useMutation({
    mutationFn: inviteUsersToConversation,
    onSuccess: () => {
      visibleChatStore
        .getState()
        .addMembers(selectedUsers.map(user => user.id));
      handleClose();
    },
  });
  const {t} = useTranslation();

  const handleNext = useCallback(() => {
    mutate({
      channel: channel,
      users: selectedUsers.map(user => user.id),
      idempotencyKey: getUlid(),
    });
  }, [channel, selectedUsers, mutate]);

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

  const footer = useMemo(
    () => ({
      primaryButton: {
        text: t('general.add'),
        onPress: handleNext,
        isLoading: isPending,
        disabled: !selectedUsers.length,
      },
    }),
    [handleNext, isPending, selectedUsers, t],
  );

  return (
    <Dialog
      isVisible={isVisible}
      onClose={handleClose}
      title={t('chat.groups.create.add_members')}
      withCloseButton
      fullScreen
      wrapperType="none"
      footer={footer}
      enableContentPanningGesture={false}>
      <View style={styles.container}>
        <InputSearch
          placeholder={t('general.search')}
          value={searchText}
          onChangeText={onChangeSearchText}
          style={styles.search}
          variant="custom"
        />
        <ChatSearchUsers
          searchText={searchText}
          selectedUsers={selectedUsers}
          setSelectedUsers={setSelectedUsers}
          selectEnabled
          isInChannel
          backgroundColor={theme.background.layout.tertiary}
        />
      </View>
    </Dialog>
  );
}

export default DialogAddMembers;
