import { useMemo } from 'react';
import { useMutation, useQuery } from 'react-query';

import { queryClient } from 'src/config/react-query';
import {
  completeSurvey,
  getSurveyTemplate,
} from 'src/pages/dashboard/serviceManagement/services';
import {
  CsatSurveyResponseBody,
  ModuleConfiguration,
  SurveyQuestion,
  Task,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useModuleConfiguration } from '../../../contexts/ModuleConfigurationContext';
import useSnackbar from '../../../hooks/useSnackbar';
import { serviceManagementKeys } from '../../../queries';

type Props = {
  task: Task;
};

const validActivationDate = (task: Task, moduleConfig: ModuleConfiguration) => {
  if (!task || !moduleConfig) {
    return false;
  }

  const taskDate = new Date(task.createdAt);
  const activationDate = new Date(moduleConfig.csatActivationDate || '');

  if (isNaN(taskDate.getTime()) || isNaN(activationDate.getTime())) {
    return false;
  }

  return taskDate >= activationDate;
};

const useCsatSurvey = ({ task }: Props) => {
  const { t } = useLokaliseTranslation('service_management');
  const { showSnackbar } = useSnackbar();

  const {
    moduleQuery: { data: moduleConfig, isLoading: isLoadingModuleConfig },
  } = useModuleConfiguration();

  // Check if the survey is enabled and the task is in a terminal state and the activation date is before the task creation date
  const surveyEnabled: boolean =
    !!moduleConfig?.csatEnabled &&
    !!task?.state?.terminal &&
    moduleConfig.csatActivationDate != null &&
    validActivationDate(task, moduleConfig);

  const shouldFetchSurveyTemplate: boolean =
    !!task &&
    !isLoadingModuleConfig &&
    surveyEnabled &&
    !!task?.catalogItem?.csatTemplateKey;

  const {
    data: surveyTemplate,
    isLoading,
    isError,
  } = useQuery(
    serviceManagementKeys.survey.template(
      task?.catalogItem?.csatTemplateKey!,
      task?.id,
    ),
    () => getSurveyTemplate(task?.catalogItem.csatTemplateKey!, task?.id),
    {
      select: data => data?.data,
      enabled: shouldFetchSurveyTemplate,
    },
  );

  const validateSurveyForm = (
    formValues: Record<string, string | undefined>,
    questions: SurveyQuestion[],
  ) => {
    if (!questions || !questions.length) {
      return false;
    }

    for (const question of questions) {
      const value = formValues[question.id];
      if (question.required && !value) {
        return false;
      }
    }

    return true;
  };

  const completeSurveyMutation = useMutation(
    (body: CsatSurveyResponseBody) => completeSurvey(body),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(
          serviceManagementKeys.survey.template(
            task?.catalogItem.csatTemplateKey!,
            task?.id,
          ),
        );
        showSnackbar({
          title: t('SURVEY_RESPONSE_SUCCESS'),
          variant: 'success',
        });
      },
      onError: () => {
        showSnackbar({
          title: t('SURVEY_RESPONSE_ERROR'),
          variant: 'error',
        });
      },
    },
  );

  const hasRespondedSurvey = useMemo(() => {
    if (!surveyTemplate || !surveyTemplate.csatQuestions?.length) {
      return false;
    }
    return surveyTemplate.csatQuestions.some(question => question.value);
  }, [surveyTemplate]);

  return {
    surveyEnabled,
    surveyTemplate,
    isLoading,
    isError,
    completeSurveyMutation,
    validateSurveyForm,
    hasRespondedSurvey,
  };
};

export default useCsatSurvey;
