import {useCallback, useRef} from 'react';
import {useTranslation} from 'react-i18next';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import {useMutation} from '@tanstack/react-query';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {SurveyTaskDetail as SurveyTaskDetailType} from '@modules/employeeLifecycle/interfaces';
import {useInvalidateTaskOnUpdate} from '@modules/employeeLifecycle/hooks';
import {startSurveyJourneyTask} from '@modules/employeeLifecycle/service';
import {RootStackParamList} from '@navigation/interfaces';
import {Screens} from '@shared/constants';

import {TaskDetailProps} from '../../interfaces';
import {BaseTaskDetail} from '../BaseTaskDetail';

export function SurveyTaskDetail({
  task,
  source,
  isUpdatingTask,
  ...rest
}: TaskDetailProps) {
  const {t} = useTranslation();
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  // SURVEY_DETAIL has no completion callback, so we track when we navigate there
  // and refetch on return to pick up any status changes (e.g. survey completed).
  const navigatedToSurvey = useRef(false);
  const surveyTask = task as SurveyTaskDetailType;

  const {invalidate} = useInvalidateTaskOnUpdate(surveyTask, source);

  useFocusEffect(
    useCallback(() => {
      if (navigatedToSurvey.current) {
        navigatedToSurvey.current = false;
        invalidate();
      }
    }, [invalidate]),
  );

  const {mutateAsync, isPending} = useMutation({
    mutationFn: startSurveyJourneyTask,
  });

  const navigateToSurveyDetail = () => {
    navigatedToSurvey.current = true;
    navigation.navigate(Screens.SURVEY_DETAIL, {
      id: surveyTask.task.surveyId,
      source: source.toLowerCase(),
    });
  };

  const onGoToSurveyDetail = async () => {
    if (!surveyTask.taskInfo.participantAdded) {
      await mutateAsync(surveyTask.id, {
        onSuccess: navigateToSurveyDetail,
      });
      return;
    }

    navigateToSurveyDetail();
  };

  return (
    <BaseTaskDetail
      {...rest}
      task={task}
      isUpdatingTask={isUpdatingTask}
      pendingAction={{
        text: t(
          surveyTask.taskInfo.participantAdded
            ? 'employee_lifecycle.survey_task_detail.resume_survey'
            : 'employee_lifecycle.survey_task_detail.start_survey',
        ),
        onPress: onGoToSurveyDetail,
        isLoading: isPending,
      }}
    />
  );
}
