import { observer } from 'mobx-react-lite';
import React, { useEffect } from 'react';
import { useCustomFieldsWidgetContext } from '../CustomFieldsWidgetContext';
import { CustomFieldsWidgetBaseProps } from './types';

const _CustomFieldsWidgetContentLazy = ({
  emptyStateOverrides,
  onChange,
}: {
  emptyStateOverrides: CustomFieldsWidgetBaseProps['emptyStateOverrides'];
  onChange?: CustomFieldsWidgetBaseProps['onChange'];
}) => {
  const state = useCustomFieldsWidgetContext();
  const WidgetContent = state.CustomFieldsWidgetContent!;

  useEffect(() => {
    return state.initContent();
  }, []);

  return (
    <div
      ref={(widgetContentRef) => {
        state.setWidgetContentRef(widgetContentRef);
      }}
    >
      <WidgetContent
        state={state}
        emptyStateOverrides={emptyStateOverrides}
        onChange={onChange}
      />
    </div>
  );
};

export const CustomFieldsWidgetContentLazy = observer(
  _CustomFieldsWidgetContentLazy,
);
