import { useCallback, useMemo } from 'react';
import Debug from 'debug';

import type { ServiceTypes } from '~/lib/types';
import type { FC } from 'react';
import type { AddLinkPickStageProps } from '../../../lib/AddLinkDialogBox';

import Box from '~/src/components/Box';
import DialogBox from '~/src/components/DialogBox';
import { useEditActions } from '~/src/components/ItemPage/ItemPageEdit/useEditActions';
import useHash from '~/src/hooks/useHash';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import { useI18n } from '~/src/lib/i18n';
import { AddLinkPickStage } from '../../../lib/AddLinkDialogBox';
import AddLinkCreateStage from '../../../lib/AddLinkDialogBox/AddLinkCreateStage';

const debug = Debug('songwhip/AddSubscribeButtonDialog');

interface AddPresaveButtonDialogProps {
  items: AddLinkPickStageProps['items'];
  onClose: () => void;
  onPickService: (serviceType: ServiceTypes) => void;
  onCreateLink: (dataPath: string) => void;
  hashParam: string;
}

// TODO: migrate to <DialogBoxWithStages>
const AddPresaveButtonDialog: FC<AddPresaveButtonDialogProps> = ({
  items,
  onClose,
  onCreateLink,
  onPickService,
  hashParam,
}) => {
  const { setHashParam, hashParams } = useHash();
  const { addCustomLinkObject: addCustomLink } = useEditActions();
  const isLargeScreen = useIsLargeScreen();
  let stage = hashParams[hashParam];
  const { t } = useI18n('itemEdit');

  // when there are no items to show, jump straight to the create link stage
  if (!items.length) {
    stage = 'create';
  }

  const initialStage = useMemo(() => stage, []);

  return (
    <DialogBox
      fillViewport={!isLargeScreen}
      onClose={onClose}
      testId="addSubscribeButtonDialog"
      contentKey={stage}
      renderContent={useCallback(
        ({ close }) => {
          return (
            <Box coverParent={!isLargeScreen}>
              {(() => {
                switch (stage) {
                  default:
                    return (
                      <AddLinkPickStage
                        items={items}
                        coverParent={!isLargeScreen}
                        height={isLargeScreen && !stage ? '30rem' : undefined}
                        onBack={close}
                        inputPlaceholder={t(
                          'presaveButtons2.addItemDialogTitle'
                        )}
                        inputTextSize="1.7rem"
                        onPick={({ item }) => {
                          debug('on pick', item);
                          onPickService(item.serviceType!);
                          close();
                        }}
                        onCreate={(params) => {
                          const dataPath = addCustomLink(params);

                          debug('on create', params, dataPath);

                          onCreateLink(dataPath);
                          close();
                        }}
                        onCreateCustom={(link) => {
                          setHashParam({
                            [hashParam]: 'create',
                            link,
                          });
                        }}
                      />
                    );

                  case 'create':
                    return (
                      <AddLinkCreateStage
                        onCreate={({ dataPath }) => {
                          debug('on create', dataPath);
                          onCreateLink(dataPath);
                          close();
                        }}
                        // show the close button when the first stage was 'create'
                        onClose={initialStage === 'create' && close}
                        // show the back button when first stage wasn't 'create'
                        onBack={
                          initialStage !== 'create' &&
                          (() => {
                            setHashParam({
                              [hashParam]: '',
                              link: undefined,
                            });
                          })
                        }
                      />
                    );
                }
              })()}
            </Box>
          );
        },
        [stage, isLargeScreen, items]
      )}
    />
  );
};

export default AddPresaveButtonDialog;
