// @ts-expect-error -- ?island not typed
import FormIsland from './islands/FormIsland.js?island';
// @ts-expect-error -- ?island not typed
import LegacyFormIsland from './islands/LegacyFormIsland.js?island';
import { FormProps } from './types.js';
import { Island, useEditorVariableChecks } from '@hubspot/cms-components';
import ContentFields from './ContentFields.js';
import StyleFields from './StyleFields.js';
import PlaceholderForm from './PlaceholderForm.js';

const FormComponent = ({
  formField,
  formId,
  formVersion,
  variant = 'form1',
  ...rest
}: FormProps) => {
  const resolvedFormId = formField != null ? formField.form_id : formId;
  const resolvedVersion =
    formField != null ? formField.embed_version : formVersion;
  const isV4 = resolvedVersion === 'v4';
  const FormModule = isV4 ? FormIsland : LegacyFormIsland;
  const editorChecks = useEditorVariableChecks();
  const hasFormData = !!resolvedFormId;

  if (!hasFormData && !editorChecks.is_in_editor) return null;

  if (!hasFormData) {
    return (
      <div data-form-variant={variant} data-button-variant="primaryButton">
        <PlaceholderForm />
      </div>
    );
  }

  return (
    <Island
      module={FormModule}
      data-form-variant={variant}
      formId={resolvedFormId}
      variant={variant}
      {...rest}
    />
  );
};

type FormComponentType = typeof FormComponent & {
  ContentFields: typeof ContentFields;
  StyleFields: typeof StyleFields;
};

const Form = FormComponent as FormComponentType;
Form.ContentFields = ContentFields;
Form.StyleFields = StyleFields;

export default Form;
