import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import classNames from 'clsx';

import { getIAB } from '@/modules/@common/iab/helpers';
import { getToken } from '@/modules/@common/token/helpers';
import { getUserDataSelector } from '@/modules/@common/user/redux/selectors';
import { redirectToSupportedNewFeedForm } from '@/modules/feeds/Editor/helpers/injectNewFeedFormUtil';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import store from '@/modules/@common/store';

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

const containerId = 'pcn-root';

function PCNProxy() {
  const user = useSelector(getUserDataSelector);
  const renderApp = !!user && !!Object.keys(user).length;

  if (typeof window !== 'undefined') {
    // @ts-expect-error proxy notification for old components
    window.PCNProxy = {
      token: getToken(),
      user,
      iab: getIAB(),
      // @ts-expect-error proxy notification for old components
      redirectToSupportedNewFeedForm: (...args) => redirectToSupportedNewFeedForm(...args),
      // @ts-expect-error proxy notification for old components
      showNotificationAction: (...args) => store.current.dispatch(showNotificationAction(...args)),
    };
  }

  useEffect(() => {
    if (renderApp) {
      document.documentElement.classList.add('pcn-page');

      const script = document.createElement('script');
      script.src = '/api/pcn-legacy/embed-script';
      script.type = 'module';

      document.getElementById(containerId)!.appendChild(script);

      // @ts-expect-error proxy notification for old components
      window.PCNInitRoot?.({
        token: getToken(),
        user,
        iab: getIAB(),
      });
    }

    return () => {
      document.documentElement.classList.remove('pcn-page');
    };
  }, [renderApp]);

  return (
    <div className={classNames(styles.Wrapper, { [styles.Wrapper___loading]: !renderApp })}>
      {renderApp ? <div id={containerId} /> : null}
    </div>
  );
}

export default PCNProxy;
