import { useEffect, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useNavigate, useParams } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import useGeneralError from 'src/hooks/useGeneralError';
import useNewTheme from 'src/hooks/useNewTheme';
import { type Audience } from 'src/types/segmentation';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import useAudienceMutation from '../hooks/useAudienceMutation';
import useCourseStatus from '../hooks/useCourseStatus';
import useCreateDraftMutation from '../hooks/useCreateDraftMutation';
import useEditCourse from '../hooks/useEditCourse';
import useGetAudience from '../hooks/useGetAudience';
import useGetCourse from '../hooks/useGetCourse';
import useUpdateDraftMutation from '../hooks/useUpdateDraftMutation';
import { coursesRoutes } from '../routes';
import { type OnDraftProps, Steps, type StepsTypes } from '../types';

import CourseForm from './components/CourseForm';

export const New = () => {
  const params = useParams();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('learning');
  const NewThemeProvider = useNewTheme();

  const paramCourseId = params.id ? parseInt(params.id) : undefined;
  const [courseId, setCourseId] = useState(paramCourseId);
  const { isEdit, isDuplicate, isDraftEdit, isCreate } = useCourseStatus();

  useEffect(() => {
    logEvent(LogEvents.NEW_COURSE_INICIATED);
  }, []);

  const course = useGetCourse({
    courseId,
    options: {
      onError: err => {
        navigate(coursesRoutes.base());
        showGeneralError(err, t('general:not_found'));
      },
    },
  });

  const audience = useGetAudience(courseId);
  const createDraftMutation = useCreateDraftMutation();
  const audienceMutation = useAudienceMutation();
  const updateDraftMutation = useUpdateDraftMutation();
  const editCourseMutation = useEditCourse();

  const isLoadingMutations =
    createDraftMutation.isLoading ||
    updateDraftMutation.isLoading ||
    audienceMutation.isLoading ||
    editCourseMutation.isLoading;

  const isNotNewCourse = isEdit || isDraftEdit || isDuplicate;
  const isLoadingContent = course.isLoading || audience.isLoading;

  const handleSubmit = async (values: StepsTypes, prevValues?: StepsTypes) => {
    if (!courseId) return;
    await editCourseMutation.mutateAsync({ courseId, values, prevValues });
  };

  const handleDraft = async ({
    values,
    deletedModules,
    deletedTasks,
    currentStep,
  }: OnDraftProps) => {
    const shouldCreateDraft = !courseId && isCreate;

    let currentCourseId = courseId;

    if (shouldCreateDraft) {
      const response = await createDraftMutation.mutateAsync(values);
      currentCourseId = response.data.id;
      setCourseId(currentCourseId);
    }

    if (!currentCourseId) throw new Error('Draft course ID is required');

    const updatedCourse = await updateDraftMutation.mutateAsync({
      courseId: currentCourseId,
      values,
      deletedModules,
      deletedTasks,
    });

    // This step will not affect final audience but is necessary to have the audience updated in the draft.
    // We repeat this mutation in the onSuccess callback in `editCourseMutation` to set the final audience
    // once the course is "ACTIVE".
    // src/pages/dashboard/Learning/Courses/hooks/useEditCourse.ts line 43
    let updatedAudience: Audience | undefined = audience.data;
    if (currentStep === Steps.CONFIGURATION) {
      await audienceMutation.mutateAsync({ courseId: currentCourseId, values });
      updatedAudience = (await audience.refetch()).data;
    }

    return { updatedCourse: updatedCourse.data, updatedAudience };
  };

  if (isNotNewCourse && isLoadingContent) {
    return <HuCircularProgress centered />;
  }

  return (
    <NewThemeProvider>
      <Helmet>
        <title>
          {formatTitle(t(isEdit ? 'course.edit' : 'course.create'))}
        </title>
      </Helmet>
      <Stack
        sx={{
          height: '100%',
          '& hr + div': {
            ...(isLoadingMutations && {
              opacity: 0.5,
              pointerEvents: 'none',
            }),
          },
        }}
      >
        <CourseForm
          course={course.data}
          audience={audience.data}
          onDraft={handleDraft}
          onSubmit={handleSubmit}
          loadingMutations={isLoadingMutations}
        />
      </Stack>
    </NewThemeProvider>
  );
};

export default New;
