import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

import CircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import useSnackbar from '@material-hu/components/design-system/Snackbar';
import Stack from '@material-hu/mui/Stack';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { ShiftsSelectionProvider } from '../../../contexts/ShiftsSelectionContext';
import { useGetShiftRotationById } from '../../../hooks/useGetShiftRotationById';
import { shiftsRoutes } from '../../../routes';
import { parseRotationToFormData } from './parseRotationToFormData';
import { SHIFT_ROTATION_INITIAL_VALUES } from '../../../form';
import CreateShiftRotationContent from './CreateShiftRotationContent';

const CreateShiftRotationProvider = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('shifts');
  const { enqueueSnackbar } = useSnackbar();

  const { rotation, isLoading, isError } = useGetShiftRotationById(id);

  useEffect(() => {
    if (id && isError) {
      enqueueSnackbar({
        title: t('error_load_shift_rotations'),
        variant: 'error',
      });
      navigate(shiftsRoutes.templates());
    }
  }, [id, isError, enqueueSnackbar, navigate, t]);

  // In edit mode, wait until the rotation graph is available before mounting
  // the form so it receives correct defaultValues from the start.
  const isEditPending = !!id && isLoading;
  const isEditReady = !!id && !!rotation;
  const isCreate = !id;

  const defaultValues = isEditReady
    ? parseRotationToFormData(rotation)
    : SHIFT_ROTATION_INITIAL_VALUES;

  return (
    <>
      {isEditPending && (
        <Stack
          sx={{
            height: '100%',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <CircularProgress />
        </Stack>
      )}
      {(isCreate || isEditReady) && (
        <CreateShiftRotationContent
          defaultValues={defaultValues}
          rotationId={id}
        />
      )}
    </>
  );
};

const CreateShiftRotation = () => {
  const HuGoThemeProvider = useHuGoTheme();

  return (
    <HuGoThemeProvider>
      <ShiftsSelectionProvider>
        <CreateShiftRotationProvider />
      </ShiftsSelectionProvider>
    </HuGoThemeProvider>
  );
};

export default CreateShiftRotation;
