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

declare global {
  interface Window {
    hbspt?: {
      forms: {
        create: (options: {
          portalId: number;
          formId: string;
          env: 'qa' | 'prod';
          target: string;
        }) => void;
      };
    };
  }
}

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

const LegacyFormIsland = ({ formId, variant }: FormProps) => {
  const portalId = getHubID();
  const resolvedEnv = getHSEnv();
  const rawId = useId();
  const containerId = `hs-legacy-form-${rawId.replace(/:/g, '')}`;

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

    const scriptSrc = getScriptSrc(resolvedEnv);

    const createForm = () => {
      window.hbspt?.forms.create({
        portalId,
        formId,
        env: resolvedEnv,
        target: `#${containerId}`,
      });
    };

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

    if (existingScript) {
      if (window.hbspt) {
        createForm();
      } else {
        existingScript.addEventListener('load', createForm);
        return () => existingScript.removeEventListener('load', createForm);
      }
      return;
    }

    const script = document.createElement('script');
    script.src = scriptSrc;
    script.addEventListener('load', createForm);
    document.head.appendChild(script);

    return () => {
      script.removeEventListener('load', createForm);
      script.remove();
    };
  }, [formId, portalId, resolvedEnv, containerId]);

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

  return (
    <div
      id={containerId}
      className={styles.legacyFormStyles}
      data-form-variant={variant}
      data-button-variant="primaryButton"
    />
  );
};

export default LegacyFormIsland;
