import { useMutation, useQueryClient } from 'react-query';

import { type AxiosResponse } from 'axios';
import { cloneDeep, set } from 'lodash-es';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { backupAnswer } from '../services';
import { type SurveyResponse } from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { pxKeys } from '../queries';

type Params = {
  questionIndex: number;
  surveyId: number;
  onUpdateQuestionIndex: (questionIndex: number) => void;
};

const useBackupAnswerMutation = ({
  questionIndex,
  surveyId,
  onUpdateQuestionIndex,
}: Params) => {
  const queryClient = useQueryClient();
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('people_experience');

  const mutation = useMutation(backupAnswer, {
    onMutate: async backupPayload => {
      const queryKey = pxKeys.surveyDetail(backupPayload.surveyId);

      await queryClient.cancelQueries(queryKey);

      const prevSurvey =
        queryClient.getQueryData<AxiosResponse<SurveyResponse>>(queryKey);

      const nextSurvey = cloneDeep(prevSurvey);
      const foundQuestionIdx = prevSurvey?.data.form.questions.findIndex(
        formQuestion => formQuestion.id === backupPayload.questionId,
      );

      if (nextSurvey && foundQuestionIdx !== -1) {
        const baseUpdatePath = `data.form.questions.[${foundQuestionIdx}]`;

        set(nextSurvey, `${baseUpdatePath}.answer`, backupPayload.answer);
        set(nextSurvey, `${baseUpdatePath}.comment`, backupPayload.comment);
        set(nextSurvey, `${baseUpdatePath}.answered`, true);

        queryClient.setQueryData(queryKey, nextSurvey);
      }
      return { prevSurvey, questionIndex };
    },
    onError: (_error, backupPayload, context) => {
      queryClient.setQueryData(
        pxKeys.surveyDetail(backupPayload.surveyId),
        context?.prevSurvey?.data,
      );

      enqueueSnackbar({
        title: t('BACKUP_ANSWER_ERROR'),
        variant: 'error',
      });

      onUpdateQuestionIndex(context?.questionIndex ?? 0);
    },
    onSettled: () => {
      queryClient.invalidateQueries(pxKeys.surveyDetail(surveyId));
    },
  });

  return mutation;
};

export default useBackupAnswerMutation;
