import React, {useCallback, useLayoutEffect} from 'react';
import {useTranslation} from 'react-i18next';
import {CloseButton} from '@components';
import {useQuery} from '@hooks/queries-v5/useQuery';
import {Navigation} from '@interfaces/navigation';
import {getTaskDetail} from '@modules/serviceManagement/services';
import {serviceManagementQueryKeys} from '@modules/serviceManagement/constants';
import {Screens} from '@shared/constants';
import {FormSuccessConfirmation} from '@shared/dynamicForms';

function ServicePortalTaskSuccess({
  navigation,
  route: {
    params: {id},
  },
}: Navigation<Screens.SERVICE_PORTAL_TASK_SUCCESS>) {
  const {t} = useTranslation();
  const {data: task, isLoading} = useQuery(
    serviceManagementQueryKeys.taskDetail(id),
    () => getTaskDetail({id}),
  );

  const onGoToTasks = useCallback(
    () => navigation.popTo(Screens.SERVICE_PORTAL),
    [navigation],
  );

  useLayoutEffect(() => {
    const headerRight = () => <CloseButton onPress={onGoToTasks} />;
    navigation.setOptions({
      headerLeft: () => null,
      title: task?.catalogItem.name,
      headerRight,
    });
  }, [navigation, onGoToTasks, task?.catalogItem.name]);

  const onGoToDetail = useCallback(
    () =>
      navigation.replace(Screens.SERVICE_PORTAL_TASKS_DETAILS, {
        id,
        fistTabKey: Screens.SERVICE_MANAGEMENT_TASKS_COMMENTS_TAB,
      }),
    [id, navigation],
  );

  return (
    <FormSuccessConfirmation
      isLoading={isLoading}
      title={t('service_management.task_success_title', {
        name: task?.catalogItem.name,
      })}
      description={
        task?.catalogItem.automaticMessage ||
        t('service_management.task_success_body')
      }
      primaryButton={{
        text: t('service_management.go_to_details'),
        onPress: onGoToDetail,
      }}
      secondaryButton={{
        text: t('service_management.go_back_my_requests'),
        onPress: onGoToTasks,
      }}
    />
  );
}

export default ServicePortalTaskSuccess;
