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

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

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

import { useGetLearningCertificate } from '../../hooks/useGetLearningCertificate';
import {
  getCertificateCreateDefaultValues,
  getCertificateEditValues,
} from '../form';
import { useCertificateGuard } from '../hooks/useCertificateGuard';
import { useCertificateId } from '../hooks/useCertificateId';

import CertificateWizardForm from './CertificateWizardForm';

/**
 * Wizard entry point. Resolves the form values before mounting the form: in edit
 * mode it fetches the certificate, handles loading and the missing/failed guard,
 * and only renders the form once the persisted values are ready.
 */
const CreateCertificateWizard = () => {
  const { t } = useLokaliseTranslation('learning');
  const { palette } = useTheme();

  const routeCertificateId = useCertificateId();
  const isEditMode = !!routeCertificateId;

  const {
    data: certificate,
    isLoading: isLoadingCertificate,
    isError: isCertificateError,
  } = useGetLearningCertificate(routeCertificateId);

  useCertificateGuard({ isEditMode, isError: isCertificateError });

  const isLoadingEdit = isEditMode && (isLoadingCertificate || !certificate);

  if (isLoadingEdit) {
    return (
      <Stack
        sx={{
          minHeight: '100%',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: palette.new.background.layout.default,
        }}
      >
        <Spinner />
      </Stack>
    );
  }

  const defaultValues =
    isEditMode && certificate
      ? getCertificateEditValues(certificate, t)
      : getCertificateCreateDefaultValues(t);

  return (
    <CertificateWizardForm
      key={routeCertificateId ?? 'create'}
      defaultValues={defaultValues}
      isEditMode={isEditMode}
      initialCertificateId={certificate?.id ?? null}
      certificateName={certificate?.name}
    />
  );
};

export default CreateCertificateWizard;
