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 { useGetSession } from '../hooks/useGetSession';
import { NewStepperProvider } from '../hooks/useNewSessionStepper';
import { type NewSessionFormValues } from '../types';

import SessionForm from './components/SessionForm';
import { formatDefaultSessionValues } from './form';

const SessionNew = () => {
  const { t } = useLokaliseTranslation('learning');
  const HugoThemeProvider = useHuGoTheme();
  const params = useParams();

  const sessionRef = useRef<NewSessionFormValues | undefined>(undefined);
  const sessionId = params.id ? parseInt(params.id) : undefined;

  const { data: sessionData, isLoading, isSuccess } = useGetSession(sessionId);

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

  useEffect(() => {
    const initForm = async () => {
      const formattedValues = await formatDefaultSessionValues(sessionData);
      form.reset(formattedValues);
      sessionRef.current = formattedValues;
    };

    if (isSuccess || !sessionId) initForm();
  }, [isSuccess, sessionId, form.reset, sessionData]);

  const isLoaded = !isLoading && sessionRef.current;

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('session.create'))}</title>
      </Helmet>
      <HugoThemeProvider>
        <FormProvider {...form}>
          <NewStepperProvider>
            <SessionForm
              sessionRef={sessionRef}
              loadingSession={!isLoaded}
            />
          </NewStepperProvider>
        </FormProvider>
      </HugoThemeProvider>
    </>
  );
};

export default SessionNew;
