import * as React from 'react';
import * as PropTypes from 'prop-types';
import { usePlatform } from '../../utils/platform';
import { ConfigProvider, ImagePreview } from 'tea-component';

export function ImageInner({
  objectFit,
  style,
  className,
  alt,
  src,
  setIsError,
  events,
  lazyLoad,
  maskClosable,
  imgPreview,
}) {
  const platform = usePlatform();
  const [imgShow, setImgShow] = React.useState(false);
  const onMaskClick = () => {
    if (maskClosable) {
      setImgShow(false);
    }
  };
  if (platform === 'h5' || !imgPreview) {
    return (
      <>
        <img
          style={{
            objectFit,
            ...style,
          }}
          className={className}
          alt={alt}
          src={src}
          onLoad={(e) => {
            setIsError(false);
            events.load && events.load({}, { originEvent: e });
          }}
          onError={(e) => {
            setIsError(true);
            events.error && events.error({}, { originEvent: e });
          }}
          onClick={() => {
            if (imgPreview) {
              setImgShow(true);
            }
          }}
          loading={lazyLoad ? 'lazy' : undefined}
        />
        {imgShow && (
          <div className="weda-img-mask" onClick={onMaskClick}>
            <div
              onClick={() => setImgShow(false)}
              className="weda-img-modal-close-btn"
            >
              <i className="weui-icon-clear" style={{ color: 'white' }}></i>
            </div>
            <div
              className="weda-img-preview"
              style={{
                backgroundImage: `url(${src})`,
              }}
            ></div>
          </div>
        )}
      </>
    );
  } else {
    return (
      <ConfigProvider classPrefix="wedatea2td">
        <ImagePreview
          previewSrc={src}
          lazyLoad
          maskClosable={maskClosable}
          className={className}
          style={{ ...style, objectFit }}
        >
          {(open) => (
            <img
              style={{
                objectFit,
                cursor: 'zoom-in',
                ...style,
              }}
              className={className}
              alt={alt}
              src={src}
              onLoad={(e) => {
                setIsError(false);
                events.load && events.load({}, { originEvent: e });
              }}
              onError={(e) => {
                setIsError(true);
                events.error && events.error({}, { originEvent: e });
              }}
              loading={lazyLoad ? 'lazy' : undefined}
              onClick={open}
            />
          )}
        </ImagePreview>
      </ConfigProvider>
    );
  }
}
