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

import type { FC } from 'react';
import type {
  CustomLinksDialogProps,
  CustomLinksDialogRenderStage,
  CustomLinksDialogStages,
} from './types';

import { ItemTypes } from '~/lib/songwhipApi/types';
import locales from '~/locales/fragments/customLinksDialog';
import useFetchAccount from '~/src/hooks/useFetchAccount';
import useHash from '~/src/hooks/useHash';
import useIsEnabled from '~/src/hooks/useIsEnabled';
import { resolveCustomDomains } from '~/src/lib/customDomain';
import { useI18nStatic } from '~/src/lib/i18n';
import { Features } from '~/src/store/session/types';
import DialogBoxWithStages from '../DialogBoxWithStages';
import PageError from '../PageError';
import { AddCustomLinkStage } from './AddCustomLinkStage';
import { AddServiceLinkStage } from './AddServiceLinkStage';
import { DefaultStage } from './DefaultStage';
import { EditCustomLinkStage } from './EditCustomLinkStage';
import { EditServiceLinkStage } from './EditServiceLinkStage';
import { isServiceLink } from './types';
import { CustomLinksDialogContext } from './useCustomLinksDialogContext';

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

const CustomLinksDialog: FC<CustomLinksDialogProps> = ({
  dialogId,
  generalLink,
  item,
}) => {
  const accountId = item.primaryOwnerAccount?.id;

  const { t } = useI18nStatic<'customLinksDialog'>(locales);
  const { hashParams } = useHash();

  const isDefaultCustomLinkFeatureEnabled = useIsEnabled(
    Features.DEFAULT_CUSTOM_LINK
  );

  const { isLoading: accountIsLoading, result: account } =
    useFetchAccount(accountId);

  const customDomains = useMemo(() => {
    if (!account) return [];

    const artistPath = (
      item.type === ItemTypes.ARTIST ? item.pagePath : item.artistPagePath
    ).replace('/', '');

    return resolveCustomDomains({
      account,
      artistPath,
    });
  }, [account, item]);

  return (
    <CustomLinksDialogContext.Provider
      value={{
        customDomains,
        defaultFeature: isDefaultCustomLinkFeatureEnabled,
        accountIsLoading,
        generalLink,
        account,
        debug,
        item,
      }}
    >
      <DialogBoxWithStages
        dialogId={dialogId}
        fillViewportOnSmallScreen
        withOverflowGradients
        maxWidth="50rem"
        maxHeight="50rem"
        testId="customPageLinkDialog"
        stages={useMemo(
          () =>
            ({
              default: (props) => <DefaultStage {...props} />,
              addCustomLink: (props) => <AddCustomLinkStage {...props} />,
              editCustomLink: (props) => {
                const customLink = item.customLinks?.find(
                  ({ id }) => id === Number(hashParams.customLinkId)
                );

                return customLink ? (
                  <EditCustomLinkStage {...props} customLink={customLink} />
                ) : (
                  <PageError
                    error={new Error(t('missingDataError'))}
                    withContactButton
                  />
                );
              },
              addServiceLink: (props) => <AddServiceLinkStage {...props} />,
              editServiceLink: (props) => {
                const serviceLink = item.customLinks?.find(
                  ({ id }) => id === Number(hashParams.serviceLinkId)
                );

                return isServiceLink(serviceLink) ? (
                  <EditServiceLinkStage {...props} serviceLink={serviceLink} />
                ) : (
                  <PageError
                    error={new Error(t('missingDataError'))}
                    withContactButton
                  />
                );
              },
              // HACK: get the typings to work when used w/ useMemo()
            }) as Record<CustomLinksDialogStages, CustomLinksDialogRenderStage>,
          [item.customLinks, hashParams]
        )}
      />
    </CustomLinksDialogContext.Provider>
  );
};

export default CustomLinksDialog;
