import type { SelectedPrereleaseItem } from '~/src/store/types';
import type { LayoutData } from '../../../types';
import type { SendMarketingConsent } from '../types';
import type { StartPresaveParams } from '../useServicePresave';
import type { PresaveDialogRenderStage } from './types';

import { isServiceType } from '~/lib/types';
import Box from '~/src/components/Box';
import DialogBoxWithStages from '~/src/components/DialogBoxWithStages';
import Loading from '~/src/components/Loading';
import useHash from '~/src/hooks/useHash';
import { EmailStage, NotificationStage } from './components';
import { PresaveDialogStage } from './types';

interface PresaveDialogProps {
  item: SelectedPrereleaseItem;
  dialogId: string;
  layoutData: LayoutData;
  sendMarketingConsent: SendMarketingConsent;
  startNativePresave(params: StartPresaveParams): void;
}

const PresaveDialog = ({
  item,
  dialogId,
  layoutData,
  sendMarketingConsent,
  startNativePresave,
}: PresaveDialogProps) => {
  const { hashParams } = useHash();

  const currentStage = hashParams[dialogId];

  const dialogWidth =
    currentStage === PresaveDialogStage.Notification ||
    currentStage === PresaveDialogStage.Loading
      ? undefined
      : '52rem';

  const serviceType = isServiceType(hashParams.serviceType)
    ? hashParams.serviceType
    : undefined;

  return (
    <DialogBoxWithStages
      maxHeight="84vh"
      dialogId={dialogId}
      maxWidth={dialogWidth}
      withOverflowGradients={false}
      stages={
        {
          [PresaveDialogStage.Email]: (props) => {
            if (!serviceType) {
              throw new Error('Service is not supported');
            }

            return (
              <EmailStage
                {...props}
                dialogId={dialogId}
                item={item}
                serviceType={serviceType}
                layoutData={layoutData}
                sendMarketingConsent={sendMarketingConsent}
                startNativePresave={startNativePresave}
              />
            );
          },
          [PresaveDialogStage.Notification]: (props) => (
            <NotificationStage {...props} />
          ),
          [PresaveDialogStage.Loading]: () => (
            <Box padding="6rem">
              <Loading />
            </Box>
          ),
        } as Record<PresaveDialogStage, PresaveDialogRenderStage>
      }
    />
  );
};

export default PresaveDialog;
