import { useEffect } from 'react';
import { FormProps } from '../types.js';
import { getHubID, getHSEnv } from '@hubspot/cms-components';
import cx from '../../utils/classname.js';
import styles from './v4Form.module.scss';

const getScriptSrc = (portalId: number, env: string) => {
  const host = env === 'qa' ? 'js.hsformsqa.net' : 'js.hsforms.net';
  return `https://${host}/forms/embed/developer/${portalId}.js`;
};

const FormIsland = ({ formId, variant }: FormProps) => {
  const portalId = getHubID();
  const resolvedEnv = getHSEnv();

  useEffect(() => {
    if (!formId || !portalId) {
      return;
    }

    const scriptSrc = getScriptSrc(portalId, resolvedEnv);
    const existingScript = document.querySelector(`script[src="${scriptSrc}"]`);

    if (existingScript) {
      return;
    }

    const script = document.createElement('script');
    script.src = scriptSrc;
    document.head.appendChild(script);

    return () => {
      script.remove();
    };
  }, [formId, portalId, resolvedEnv]);

  if (!formId || !portalId) {
    return null;
  }

  /*
<script src="https://js.hsformsqa.net/forms/embed/102771136.js" defer></script>
<div class="hs-form-frame" data-env="qa" data-region="na1" data-form-id="53e5b258-4526-4012-9274-8bbe23ab2d09" data-portal-id="102771136"></div>
*/

  return (
    <div
      className={cx('hs-form-html', styles.v4FormStyles)}
      data-form-id={formId}
      data-portal-id={portalId}
      data-env={resolvedEnv}
      data-form-variant={variant}
    />
  );
};

export default FormIsland;
