import React, { useState } from 'react';
import { MediaProps } from '../Media';
import Loading from '../Loading';
import { ImageWrap } from './ImageWrap';
import {
  jsonProxy2,
  revokeJsonProxy,
  revokeJsonProxy2,
} from '@/utils/constants';
import compress from '@/utils/compress';

export interface ImageProps extends MediaProps {
  needCompress?: boolean;
  height?: number | string;
  width?: number | string;
}

const Image: React.FC<ImageProps> = ({
  media,
  cssStyle = '',
  imgCssStyle = '',
  mediaMimeType,
  needCompress,
  onLoad,
  isDetail,
  height = 'auto',
  width = 300,
}) => {
  const [hasChangedProxy, setHasChangedProxy] = useState(false);
  const [hasRemovedProxy, setHasRemovedProxy] = useState(false);
  const [isLoaded, setIsLoaded] = useState(false);
  const isGif = mediaMimeType?.includes('image/gif');
  return (
    <ImageWrap
      cssStyle={cssStyle}
      imgCssStyle={imgCssStyle}
      height={height}
      width={width}
    >
      <div className="imageContainer">
        <Loading
          cssStyle={`
          display: ${isDetail && isLoaded && 'none !important'};
          ${cssStyle}
        `}
        />
        <img
          className="image"
          src={media}
          onLoad={(el: any) => {
            if (
              isGif ||
              !needCompress ||
              media.includes('https://images.mirror-media.xyz/')
            ) {
              el.target.style.visibility = 'visible';
              onLoad?.();
              setIsLoaded?.(true);
              return;
            }
            compress(
              el.currentTarget.src,
              el.currentTarget,
              undefined,
              onLoad,
              setIsLoaded,
            );
          }}
          onError={el => {
            if (!hasChangedProxy) {
              const newImage = jsonProxy2(revokeJsonProxy(media));
              setHasChangedProxy(true);
              if (isGif || !needCompress) {
                el.currentTarget.src = newImage;
                return;
              }
              compress(newImage, el.currentTarget, true);
            } else if (!hasRemovedProxy) {
              const newImage = revokeJsonProxy2(media);
              setHasRemovedProxy(true);
              if (isGif || !needCompress) {
                el.currentTarget.src = newImage;
                return;
              }
              compress(newImage, el.currentTarget, true);
            }
          }}
        />
      </div>
    </ImageWrap>
  );
};

export default Image;
