import { useEffect, useState } from 'react';
import { toError } from '@theorchard/songwhip-utils';
import Debug from 'debug';

import type { CreateFlowStage } from '../../components/CreateFlow/types';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import DashedBox from '~/src/components/DashedBox';
import FilePicker from '~/src/components/FilePicker';
import Gradient from '~/src/components/Gradient';
import Image from '~/src/components/Image';
import { useAppAlert, useAppToast } from '~/src/components/NextApp/lib/CoreUi';
import { NotificationType } from '~/src/components/Notification';
import PageLoading from '~/src/components/PageLoading';
import Text from '~/src/components/Text';
import TransitionInOut from '~/src/components/TransitionInOut';
import { useListenOnEvent } from '~/src/hooks/useListenOnEvent';
import { useI18n } from '~/src/lib/i18n';
import useUploadImage from '~/src/lib/image/useUploadImage';
import { useTracker } from '~/src/lib/tracker/useTracker';
import { getImageSize } from '~/src/lib/utils/image';

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

const MAX_FILE_SIZE_MB = 4;
const maxFileSizeBytes = MAX_FILE_SIZE_MB * 1024 * 1024;

export const PickImageStage: CreateFlowStage = ({ events }) => {
  const [imageFile, setImageFile] = useState<File>();
  const { uploadImage } = useUploadImage({ trackingId: 'create-prerelease' });
  const { trackEvent } = useTracker();
  const appAlert = useAppAlert();
  const showToast = useAppToast();
  const [imageUrl, setImageUrl] = useState<string>();
  const [isLoading, setIsLoading] = useState(false);
  const { t } = useI18n('prerelease');

  useEffect(() => {
    setImageUrl(imageFile ? URL.createObjectURL(imageFile) : undefined);
  }, [imageFile]);

  const handleImageUpload = async () => {
    if (!imageFile) return { success: true };

    setIsLoading(true);

    try {
      const { url: imageUrl } = await uploadImage({
        file: imageFile,
        scaleToWidth: 1200,
        asType: 'jpeg',
      });

      debug('image uploaded');

      return { success: true, imageUrl };
    } catch (e) {
      const error = toError(e);

      trackEvent({
        type: 'error',
        subType: 'CREATE_PRERELEASE_ERROR',
        message: error.message,
      });

      appAlert({ content: t('failedToUploadArtwork') });

      return { success: false };
    } finally {
      setIsLoading(false);
    }
  };

  useListenOnEvent(events, 'nextButtonPressed', async () => {
    const { success, imageUrl } = await handleImageUpload();

    if (success) {
      events.emit('submit', { imageUrl });
    }
  });

  return (
    <div>
      {imageUrl && (
        <Box coverParent zIndex={0}>
          <Image
            alt=""
            src={imageUrl}
            coverParent
            fillParent
            cover
            style={{ opacity: 0.5 }}
            testId="image"
          />
        </Box>
      )}
      <TransitionInOut isVisible={!isLoading}>
        <FilePicker
          centerContent
          coverParent
          isDisabled={isLoading}
          testId="inputFile"
          accept={['image/jpeg', 'image/png']}
          onChange={async ({ file }) => {
            if (file) {
              // Check file size first - block files over 4MB
              if (file.size > maxFileSizeBytes) {
                showToast({
                  text: t('fileSizeTooLarge'),
                  type: NotificationType.ERROR,
                  timeoutSecs: 10,
                });
                return; // Don't set file or show preview
              }

              // File size is OK, set the file and check dimensions
              setImageFile(file);

              try {
                const imageSize = await getImageSize(file);
                if (imageSize.width < 1200) {
                  showToast({
                    text: t('artworkSizeWarning'),
                    type: NotificationType.WARNING,
                    timeoutSecs: 10,
                  });
                }
              } catch (error) {
                // Silently handle image size check errors
                debug('Failed to get image size:', error);
              }
            }
          }}
        >
          <DashedBox
            margin="0 0 2rem"
            style={{
              background: 'rgba(255,255,255,0.08)',
            }}
          >
            <Clickable
              tag="div"
              centerContent
              positionRelative
              isInline
              padding="2.1rem 2.6rem"
            >
              <Text
                isBold
                size="2rem"
                centered
                lineHeight="1em"
                margin="-0.1em 0 0"
                opacity={isLoading ? 0 : 1}
              >
                {imageUrl ? t('changeArtwork') : t('pickArtwork')}
              </Text>
            </Clickable>
          </DashedBox>
        </FilePicker>
      </TransitionInOut>
      {isLoading && <PageLoading text={t('creatingPage')} />}
      <Gradient
        from="transparent"
        to="rgba(0,0,0,0.7)"
        positionAbsolute
        left={0}
        right={0}
        bottom={0}
      >
        <Text
          centered
          padding="1.2em"
          size="1.1rem"
          isCentered
          isParagraph
          lineHeight={1.4}
          color="#bbb"
        >
          {t('artworkInputHelp')}
        </Text>
      </Gradient>
    </div>
  );
};
