import React, { useEffect, useState } from 'react';
import { useEntityPageContext } from '../../providers';
import { SkeletonCard } from '../SkeletonCard';
import { Extensions } from '../Extensions';
import { ExtensionsState } from '../../state/ExtensionsState';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { observer } from 'mobx-react-lite';

export interface EntityPageSlotsProps {
  /**
   * An id of the container defined in the installed on a site application that contains TPA's actions.
   */
  containerId: string;
  /**
   * Applies a data-hook HTML attribute that can be used in tests.
   */
  dataHook?: string;
  /**
   * Props passed to Slots Widgets
   */
  [x: string]: any;
}
export function _EntityPageSlots(props: EntityPageSlotsProps) {
  const { containerId, dataHook, ...rest } = props;
  const pageState = useEntityPageContext();
  const container = useWixPatternsContainer();

  const [state] = useState(() => {
    return new ExtensionsState({
      container,
      containerId,
    });
  });

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

  return !pageState ||
    pageState.isFetching ||
    state.initTask.status.isLoading ? (
    <SkeletonCard dataHook={dataHook} />
  ) : (
    <Extensions
      form={pageState.form}
      entity={pageState.entity}
      dataHook={dataHook}
      {...rest}
      state={state}
    />
  );
}

export const EntityPageSlots = observer(_EntityPageSlots);
