import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import {useMutation} from 'react-query';
import {useDispatch} from 'react-redux';
import {UserPermissions} from '@interfaces/user';
import {createChat} from '@modules/chat/services';
import {RegularChatListItem} from '@modules/chat/interfaces';
import {addChat} from '@modules/chat/redux/slices/chatsSlice';
import {RootStackParamList} from '@navigation/interfaces';
import {usePermission} from '@redux/selectors';
import {Screens} from '@shared/constants';

import {useOpenConversation} from './useOpenConversations';
import {convertHuUserToChatUser} from '../utils';
import {ConversationOpenResponse} from '../services/interfaces';
import {HuUser} from '../interfaces';

export const useInitializeChat = () => {
  const chats2Enabled = usePermission(UserPermissions.VIEW_CHATS_V2);
  const {navigate} = useNavigation<StackNavigationProp<RootStackParamList>>();
  const {openConversation, isLoading: isLoadingV2} = useOpenConversation();
  const onCreateChatMutation = useMutation(createChat);
  const dispatch = useDispatch();

  const initializeChat = async ({
    user,
    initialMessage,
    onSuccess,
  }: {
    user: HuUser;
    initialMessage?: string;
    onSuccess?: (
      response?: ConversationOpenResponse | RegularChatListItem,
    ) => void;
  }) => {
    if (chats2Enabled) {
      const chatUser = convertHuUserToChatUser(user);

      openConversation(
        {
          users: [chatUser],
        },
        {
          onSuccess: response => {
            onSuccess?.();
            navigate(Screens.CHAT_MESSAGES, {
              id: response.id,
              initialMessage,
            });
          },
        },
      );
    } else {
      const response = await onCreateChatMutation.mutateAsync(user.id);
      onSuccess?.(response);
      dispatch(addChat(response));
      navigate(Screens.CHAT_DETAIL, {
        chatId: response.chat.id,
        initialMessage,
      });
    }
  };

  return {
    initializeChat,
    isLoading: onCreateChatMutation.isLoading || isLoadingV2,
    chats2Enabled,
  };
};
