import { useEffect, useRef } from 'react';

import { useTheme } from '@material-hu/mui/styles';

const LACOMER_IFRAME_RELOAD_INTERVAL = 18 * 60 * 1000;

type LacomerWebviewProps = {
  title: string;
  url: string;
};

const LacomerWebview = ({ title, url }: LacomerWebviewProps) => {
  const theme = useTheme();
  const iframeRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    const script = document.createElement('script');
    script.innerHTML =
      'try {document.domain = "lacomer.com.mx"; document = "lacomer.com.mx"} catch (ex) {}';
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  useEffect(() => {
    const reloadIframe = () => {
      if (!iframeRef.current) return;
      const { src } = iframeRef.current;
      iframeRef.current.src = src;
    };

    const intervalId = setInterval(
      reloadIframe,
      LACOMER_IFRAME_RELOAD_INTERVAL,
    );

    return () => clearInterval(intervalId);
  }, []);

  return (
    <iframe
      ref={iframeRef}
      title={`Lacomer Webview - ${title}`}
      src={url}
      style={{
        width: '100%',
        height: '100%',
        border: `2px solid ${theme.palette.new.border.neutral.default}`,
        borderRadius: 4,
      }}
    />
  );
};

export default LacomerWebview;
