import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { CustomFieldsWidgetContextProvider } from '../CustomFieldsWidgetContext';
import { useCustomFieldsWidget } from '../../hooks/useCustomFieldsWidget';
import { CustomFieldsWidgetInline } from './CustomFieldsWidgetInline';
import { CustomFieldsWidgetCard } from './CustomFieldsWidgetCard';
import { CustomFieldsWidgetBaseProps, CustomFieldsWidgetProps } from './types';
import { runInAction } from 'mobx';
import { CustomFieldsWidgetCommonComponents } from './CustomFieldsWidgetCommonComponents';

interface CustomFieldsWidgetWithoutStateProps
  extends Omit<CustomFieldsWidgetProps, 'fqdn' | 'state'> {
  state?: never;
  fqdn: string;
}

const _CustomFieldsWidgetBase = ({
  subtitle,
  dataHook,
  hideEmptyState,
  emptyStateOverrides = {},
  state,
  theme = 'card',
  onChange,
  extendedFields,
}: CustomFieldsWidgetBaseProps) => {
  useState(() => {
    runInAction(() => {
      state._extendedFields = extendedFields;
    });
  });

  useEffect(() => {
    runInAction(() => {
      state._extendedFields = extendedFields;
    });
  }, [extendedFields]);

  const hideWidget =
    hideEmptyState &&
    (state.isLoading || state.dataExtension.availableCustomFields.length === 0);

  return (
    <CustomFieldsWidgetContextProvider value={state}>
      <CustomFieldsWidgetCommonComponents state={state} />
      {!hideWidget &&
        (theme === 'card' ? (
          <CustomFieldsWidgetCard
            state={state}
            emptyStateOverrides={emptyStateOverrides}
            subtitle={subtitle}
            dataHook={dataHook}
            onChange={onChange}
          />
        ) : (
          <CustomFieldsWidgetInline
            state={state}
            emptyStateOverrides={emptyStateOverrides}
            onChange={onChange}
            dataHook={dataHook}
          />
        ))}
    </CustomFieldsWidgetContextProvider>
  );
};

const CustomFieldsWidgetBase = observer(_CustomFieldsWidgetBase);

const _CustomFieldsWidgetWithoutState = (
  props: CustomFieldsWidgetWithoutStateProps,
) => {
  const state = useCustomFieldsWidget(props);
  return <CustomFieldsWidgetBase {...props} state={state} />;
};

const CustomFieldsWidgetWithoutState = observer(
  _CustomFieldsWidgetWithoutState,
);

const _CustomFieldsWidget = (props: CustomFieldsWidgetProps) => {
  return props.state ? (
    <CustomFieldsWidgetBase {...props} />
  ) : (
    <CustomFieldsWidgetWithoutState {...props} />
  );
};

export const CustomFieldsWidget = observer(_CustomFieldsWidget);
