import { useMutation } from 'react-query';

import { AxiosResponse } from 'axios';

import useGeneralError from 'src/hooks/useGeneralError';
import { getStream, stopLiveStream } from 'src/services/streaming';
import { GroupPost } from 'src/types/groups';
import { Post } from 'src/types/posts';
import { extractTextFromHTML } from 'src/utils/feed';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useStreamDestination } from './useStreamDestination';

type Params = {
  bodyHtml?: string;
  streamId?: string;
  sendNotification?: boolean;
  commentsEnabled?: boolean;
  onCreate?: () => void;
  onStart?: (param: AxiosResponse<Post | GroupPost>) => void;
  onStartError?: () => void;
  onFinish?: () => void;
};

export const useStreamActions = ({
  onStart,
  onStartError,
  onFinish,
  onCreate,
  bodyHtml,
  commentsEnabled,
  sendNotification,
  streamId,
}: Params) => {
  const { t } = useLokaliseTranslation('livestream');
  const showGeneralError = useGeneralError();
  const { actions: destinationActions } = useStreamDestination();

  const { plainText, mentions } = extractTextFromHTML(bodyHtml);
  const { mutate: goLiveMutate, isLoading: isLoadingGoLive } = useMutation(
    () =>
      destinationActions.createPost({
        streamId,
        body: bodyHtml ? plainText : '',
        bodyHtml: bodyHtml || '',
        sendNotification: sendNotification || false,
        commentsEnabled,
        attachments: [],
        segmentationItemIds: [],
        ...(!!mentions?.length && {
          bodyAttributes: mentions,
          taggedUserIds: mentions.map(mention => mention.type.user.id),
        }),
      }),
    {
      onError: error => {
        onStartError?.();
        showGeneralError(error, t('ERROR_START_STREAM'));
      },
      onSuccess: data => {
        onStart?.(data);
      },
    },
  );

  const { mutate: stopLiveMutate, isLoading: isLoadingStopLive } = useMutation(
    () => stopLiveStream(streamId || ''),
    {
      onSuccess: () => {
        onFinish?.();
      },
      onError: error => {
        showGeneralError(error, t('ERROR_END_STREAM'));
      },
    },
  );

  const {
    data: streamData,
    mutate: createMutate,
    isLoading: isLoadingCreate = true,
  } = useMutation(
    (variables: { userLanguage?: string }) => getStream(variables.userLanguage),
    {
      onError: error => {
        showGeneralError(error, t('ERROR_STREAM_INFO'));
      },
      onSuccess: () => {
        onCreate?.();
      },
    },
  );

  return {
    streamData,
    createMutate,
    isLoadingCreate,
    goLiveMutate,
    isLoadingGoLive,
    stopLiveMutate,
    isLoadingStopLive,
  };
};
