import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';

import { Paper } from '@/mui/components';

import styles from './styles.module.scss';

function PlayerPreview({
  id,
  onWidgetUpdate,
  conf = null,
  publisherId = 'lre_demo_page',
  widgetId = 'widget_noAds_TR',
}) {
  const iframeRef = useRef(null);
  const [iframeHeight, setIframeHeight] = useState('auto');

  useEffect(() => {
    const timer = setInterval(() => {
      const body = iframeRef.current?.contentWindow?.document?.body;

      if (body) {
        setIframeHeight(body.scrollHeight ?? 'auto');
      }
    }, 500);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <Paper
      key={id}
      style={{
        height: iframeHeight,
      }}
      component="iframe"
      elevation={5}
      ref={iframeRef}
      className={styles.PlayerIframe}
      title={`player-form-preview?publisher=${publisherId}&widget=${widgetId}`}
      src={`/live/_preview?publisher=${publisherId}&widget=${widgetId}&id=${id}`}
      onLoad={(event) => {
        event.target.contentWindow.ac_lre_conf_override = { ...conf };

        event.target.contentWindow.addEventListener('PlayerLiveReady', (e) => onWidgetUpdate(e.detail));
      }}
    />
  );
}

PlayerPreview.propTypes = {
  conf: PropTypes.shape({}).isRequired,
  id: PropTypes.string.isRequired,
  publisherId: PropTypes.string,
  widgetId: PropTypes.string,
  onWidgetUpdate: PropTypes.func.isRequired,
};

export default PlayerPreview;
