import { useEffect, useRef } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import useGetAudience from '../hooks/useGetAudience';
import useGetPath from '../hooks/useGetPath';
import { NewStepperProvider } from '../hooks/useNewPathStepper';
import { type NewPathFormValues } from '../types';

import PathForm from './components/PathForm';
import { formatDefaultPathValues } from './formatters';

const PathNew = () => {
  const { t } = useLokaliseTranslation('learning');
  const HugoThemeProvider = useHuGoTheme();
  const { id } = useParams();
  const pathId = id ? parseInt(id) : null;

  const { data: pathData, isLoading: loadingPath } = useGetPath(pathId);
  const { data: audienceData, isLoading: loadingAudience } =
    useGetAudience(pathId);

  const pathRef = useRef<NewPathFormValues | null>(null);

  const isDataLoaded = pathData !== undefined && audienceData !== undefined;

  const form = useForm<NewPathFormValues>({
    defaultValues: {},
    mode: 'onChange',
  });

  useEffect(() => {
    if (!pathId) {
      logEvent(LogEvents.NEW_PATH_INICIATED);
    }
  }, [pathId]);

  useEffect(() => {
    const initForm = async () => {
      const formattedValues = await formatDefaultPathValues(
        pathData,
        audienceData,
      );
      form.reset(formattedValues);
      pathRef.current = formattedValues;
    };

    if (isDataLoaded || !pathId) {
      initForm();
    }
  }, [isDataLoaded, pathId]);

  const isLoaded = !loadingPath && !loadingAudience && pathRef.current;

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('path.create'))}</title>
      </Helmet>
      <HugoThemeProvider>
        <FormProvider {...form}>
          <NewStepperProvider>
            <PathForm
              loadingPath={!isLoaded}
              pathRef={pathRef}
            />
          </NewStepperProvider>
        </FormProvider>
      </HugoThemeProvider>
    </>
  );
};

export default PathNew;
