import React, { useEffect, useRef, useState } from 'react';
import Loading from '../Loading';
import { HtmlWrap } from './HtmlWrap';
import { MediaBasicProps } from '.';

const Html: React.FC<MediaBasicProps> = ({
  media,
  mediaVisible,
  isDetail = true,
}) => {
  const contentElement = useRef<any>(null);
  const [url, setUrl] = useState<string>(media);
  const [iframeVisible, setIframeVisible] = useState<boolean>();
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => {
    const a = media.lastIndexOf('http');
    if (a === -1) {
      return;
    }
    const b = media.slice(a);
    try {
      const c = decodeURIComponent(decodeURIComponent(b));
      if (c.includes('</svg>')) {
        setIframeVisible(false);
        setUrl(
          `data:image/svg+xml;base64,${window.btoa(
            unescape(encodeURIComponent(media)),
          )}`,
        );
        return;
      }
      setIframeVisible(true);
      setUrl(c);
    } catch {
      try {
        if (media.includes('</svg>')) {
          setIframeVisible(false);
          setUrl(
            `data:image/svg+xml;base64,${window.btoa(
              unescape(encodeURIComponent(media)),
            )}`,
          );
        }
      } catch {}
    }
  }, [media]);

  return (
    <HtmlWrap mediaVisible={mediaVisible}>
      <div ref={contentElement} className="hideScrollbar">
        <Loading
          cssStyle={`
          display: ${isDetail && isLoaded && 'none'};
          z-index: ${!isDetail && isLoaded ? '-1' : '1'};
          background: ${isDetail && 'white'};
        `}
        />

        {iframeVisible ? (
          <iframe
            title="iframe"
            src={url}
            allowFullScreen
            name="mapFrame"
            scrolling="no"
            frameBorder="0"
            width="100%"
            height="100%"
            onLoad={() => setIsLoaded(true)}
            className="htmlIframe"
          />
        ) : (
          <img src={url} onLoad={() => setIsLoaded(true)} className="htmlImg" />
        )}
      </div>
    </HtmlWrap>
  );
};

export default Html;
