import { useRef } from 'react';

import type { FC } from 'react';
import type { ImageUploaderProps } from '../../components/ImageUploader';

import { AddonTypes } from '~/lib/songwhipApi/types';
import Form, { FORM_SECTION_SPACING } from '~/src/components/Form';
import InputLabel from '~/src/components/InputLabel';
import { Select } from '~/src/components/Select2';
import useFetchSessionUser from '~/src/hooks/useFetchSessionUser';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import { DEVICE_WIDTH_BREAKPOINT } from '~/src/lib/device/constants';
import { useI18n } from '~/src/lib/i18n';
import deleteImage from '~/src/lib/image/deleteImage';
import { useItemContext } from '../../../ItemPageContext';
import ResetButton from '../../../ItemPageEdit/components/ResetButton';
import { useEditActions } from '../../../ItemPageEdit/useEditActions';
import ImageUploader from '../../components/ImageUploader';
import InlineNotification from '../../components/InlineNotification';

const PREFERRED_WIDTH = 1200;
const MIN_WIDTH = 360 * 2;

const MobileSingleColumnImageSettings: FC = () => {
  const imageUploaderApiRef: ImageUploaderProps['apiRef'] = useRef(null);
  const itemContext = useItemContext();
  const { setAddon } = useEditActions();
  const { userAccountId } = useFetchSessionUser();
  const isLargeScreen = useIsLargeScreen();
  const { t } = useI18n('itemEdit');

  const liveCustomMobileImageUrl =
    itemContext.originalItemContext?.layout.settings.mobileSingleColumn.image
      .url;

  const layoutSettings = itemContext.layout.settings;
  const mobileImage = layoutSettings.mobileSingleColumn.image;
  const imageLayout = layoutSettings.mobileSingleColumn.image.layout;
  const userSettings = itemContext.addons[AddonTypes.LAYOUT_SETTINGS];

  // if the raw addon has no desktopSingleColumn settings defined then we know we're using defaults
  const isDefaultSettings = !userSettings?.mobileSingleColumn;

  const deleteOldImage = (url: string | undefined) => {
    // So long as the replaced image url is not a current live image we
    // can delete it (this will no-op if it's not a songwhip-image)
    if (url && url !== liveCustomMobileImageUrl) {
      deleteImage(url, userAccountId);
    }
  };

  return (
    <Form>
      <ImageUploader
        apiRef={imageUploaderApiRef}
        maxWidth={PREFERRED_WIDTH}
        minWidth={MIN_WIDTH}
        initialImage={mobileImage}
        testId="mobileImagePicker"
        description={t('imageSettings.imageRequirements', {
          minWidth: MIN_WIDTH,
        })}
        onSuccess={async (image) => {
          const prevMobileImage = mobileImage?.url;

          setAddon(AddonTypes.LAYOUT_SETTINGS, {
            ...userSettings,

            mobileSingleColumn: {
              ...userSettings?.mobileSingleColumn,
              image,
            },
          });

          deleteOldImage(prevMobileImage);
        }}
      />
      <InputLabel value="Image position" margin={`${FORM_SECTION_SPACING} 0 0`}>
        <Select
          options={[
            {
              text: t('imageSettings.fitImageAbove'),
              id: 'fit' as const,
              caption: t('imageSettings.fitImageAboveDescription'),
            },
            {
              text: t('imageSettings.fadeImage'),
              id: 'fade' as const,
              caption: t('imageSettings.fadeImageDescription'),
            },
          ]}
          onChange={({ value }) => {
            setAddon(AddonTypes.LAYOUT_SETTINGS, {
              ...userSettings,

              mobileSingleColumn: {
                ...userSettings?.mobileSingleColumn,

                image: {
                  ...userSettings?.mobileSingleColumn?.image,

                  layout: {
                    ...userSettings?.mobileSingleColumn?.image?.layout,
                    type: value,
                  },
                },
              },
            });
          }}
          value={imageLayout.type}
          width="100%"
        />
      </InputLabel>
      {imageLayout.type === 'fade' && (
        <InputLabel
          value="Space above content"
          margin={`${FORM_SECTION_SPACING} 0 0`}
        >
          <Select
            options={[
              {
                text: t('imageSettings.none'),
                id: 'none' as const,
              },
              {
                text: t('imageSettings.medium'),
                id: 'medium' as const,
              },
              {
                text: t('imageSettings.large'),
                id: 'large' as const,
              },
            ]}
            onChange={({ value }) => {
              setAddon(AddonTypes.LAYOUT_SETTINGS, {
                ...userSettings,

                mobileSingleColumn: {
                  ...userSettings?.mobileSingleColumn,

                  image: {
                    ...userSettings?.mobileSingleColumn?.image,

                    layout: {
                      type: 'fade',
                      spaceAboveContent: value,
                    },
                  },
                },
              });
            }}
            value={imageLayout.spaceAboveContent}
            width="100%"
          />
        </InputLabel>
      )}
      {/* render the reset button only if there are user settings defined */}
      {!isDefaultSettings && (
        <ResetButton
          onClick={() => {
            // clear the image picker so that the default image is rendered again
            imageUploaderApiRef.current?.clear();

            setAddon(AddonTypes.LAYOUT_SETTINGS, {
              ...userSettings,
              mobileSingleColumn: undefined,
            });
          }}
        />
      )}
      {isLargeScreen && (
        <InlineNotification
          margin={`${FORM_SECTION_SPACING} 0 0`}
          text={t('imageSettings.mobilePreviewWarning', {
            breakpointPx: DEVICE_WIDTH_BREAKPOINT,
          })}
        />
      )}
    </Form>
  );
};

export default MobileSingleColumnImageSettings;
