import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import { stringify } from 'qs';

import {
  DESKTOP_USER_AGENT,
  EXTERNAL_PLAYER_CONFIG_KEY,
  MOBILE_USER_AGENT,
} from '@/modules/players/PlayerIframeView/constants';

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

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

const PLAYER_PREVIEW_URL = '/player/_preview';

function PlayerIframeView(props) {
  const key = useMemo(() => Date.now(), [JSON.stringify(props)]);

  return (
    <div
      key={key}
      className={classNames(styles.Wrapper, {
        [styles.Wrapper___mobile]: props.mobile,
      })}
    >
      <Paper
        elevation={12}
        className={classNames(styles.IframeWrapper, {
          [styles.IframeWrapper___mobile]: props.mobile,
        })}
      >
        <Paper
          elevation={5}
          component="iframe"
          className={styles.Iframe}
          title="player-self-serve-preview"
          src={`${PLAYER_PREVIEW_URL}?${stringify({
            publisherName: props.publisherName,
            widgetName: props.widgetName,
            mobile: props.mobile,
            key,
          })}`}
          onLoad={(event) => {
            Object.defineProperty(
              event.target.contentWindow.navigator,
              'userAgent',
              props.mobile ? { get: () => MOBILE_USER_AGENT } : { get: () => DESKTOP_USER_AGENT },
            );
            event.target.contentWindow[EXTERNAL_PLAYER_CONFIG_KEY] = props;

            if (event.target.contentWindow.location.pathname !== PLAYER_PREVIEW_URL) {
              window.location.reload();
            }
          }}
        />
      </Paper>
    </div>
  );
}

PlayerIframeView.propTypes = {
  publisherName: PropTypes.string.isRequired,
  widgetName: PropTypes.string.isRequired,
  mobile: PropTypes.bool.isRequired,
};

export default PlayerIframeView;
