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

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

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

const FORM_BUILDER_TAG = 'ac-lre-form-builder';
const FORM_BUILDER_CONTAINER = '.form-container';

function FormPreview(props) {
  const [formBuilderInstanceRef, setBuilderInstanceRef] = useState(null);
  const [iframeHeight, setIframeHeight] = useState('auto');

  useEffect(() => {
    if (formBuilderInstanceRef) {
      formBuilderInstanceRef.showForm(props.metadata);
      const $formBuilderContent = formBuilderInstanceRef.target
        ?.querySelector(FORM_BUILDER_TAG)
        ?.querySelector(FORM_BUILDER_CONTAINER);

      if ($formBuilderContent) {
        $formBuilderContent.style.overflow = 'hidden';
      }

      setIframeHeight(formBuilderInstanceRef.getSize()?.content?.height || 'auto');
    }
  }, [formBuilderInstanceRef, props.metadata]);

  return (
    <Paper
      component="iframe"
      elevation={5}
      style={{ height: iframeHeight }}
      className={styles.Iframe}
      title="player-form-preview"
      src="/forms/_preview"
      onLoad={(event) => {
        event.target.contentDocument.defaultView.addEventListener('FormBuilderReady', (event$) => {
          setBuilderInstanceRef(event$.detail);
        });
      }}
    />
  );
}

FormPreview.propTypes = {
  metadata: PropTypes.shape({}).isRequired,
};

export default FormPreview;
