import { lazy, Suspense, useEffect, useRef } from 'react';

import Container from '@material-hu/mui/Container';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import Stepper from '@material-hu/components/design-system/Stepper';

import { appearFromTop } from 'src/constants/animation';
import { LearningFormSkeleton } from 'src/pages/dashboard/Learning/common/components/LearningFormSkeleton';
import { SessionSteps } from 'src/pages/dashboard/Learning/Sessions/constants';
import { useNewSessionStepper } from 'src/pages/dashboard/Learning/Sessions/hooks/useNewSessionStepper';

const SessionBasicInformation = lazy(() => import('./SessionBasicInformation'));
const SessionConfiguration = lazy(() => import('./SessionConfiguration'));
const SessionSegmentation = lazy(() => import('./SessionSegmentation'));
const SessionRevision = lazy(() => import('./SessionRevision'));

const STEP_CONTENT = {
  [SessionSteps.BASIC_INFORMATION]: () => <SessionBasicInformation />,
  [SessionSteps.CONFIGURATION]: () => <SessionConfiguration />,
  [SessionSteps.SEGMENTATION]: () => <SessionSegmentation />,
  [SessionSteps.REVISION]: () => <SessionRevision />,
};

type SessionNewMainProps = {
  loadingSession: boolean;
};

const SessionNewMain = ({ loadingSession }: SessionNewMainProps) => {
  const { steps, currentStep } = useNewSessionStepper();
  const { palette } = useTheme();
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const Content = STEP_CONTENT[currentStep.id];

  useEffect(() => {
    scrollContainerRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
  }, [currentStep.id]);

  return (
    <Stack
      ref={scrollContainerRef}
      component="section"
      sx={{
        pb: 4,
        overflowY: 'scroll',
        position: 'relative',
        height: '100%',
        backgroundColor: palette?.hugoBackground?.neutralBg,
      }}
    >
      <Stack
        sx={{
          backgroundColor: palette?.hugoBackground?.neutralBg,
          mx: 'auto',
          width: '100%',
          zIndex: 2,
          position: 'sticky',
          top: 0,
        }}
      >
        <Stepper
          steps={steps}
          currentStep={currentStep.value}
          sx={{
            py: 4,
            px: 3,
            maxWidth: 'md',
            mx: 'auto',
            width: '100%',
          }}
        />
      </Stack>

      <Container
        key={currentStep.value}
        maxWidth="md"
        sx={{ animation: `${appearFromTop} 0.2s ease-in-out backwards` }}
      >
        {loadingSession && <LearningFormSkeleton isSessions />}
        {!loadingSession && (
          <Stack sx={{ gap: 2 }}>
            <Suspense fallback={<LearningFormSkeleton isSessions />}>
              <Content />
            </Suspense>
          </Stack>
        )}
      </Container>
    </Stack>
  );
};

export default SessionNewMain;
