import React, { useEffect, useState } from 'react';
import { PageProps } from '@wix/design-system';
import { EntityPageState } from '../../state';
import { EntityPageHeader } from '../EntityPageHeader';
import { EntityPageContent } from '../EntityPageContent';
import { EntityPageCard } from '../EntityPageCard';
import { EntityPageSlots } from '../EntityPageExtensions';
import { EntityPageMainContent } from '../EntityPageMainContent';
import { EntityPageAdditionalContent } from '../EntityPageAdditionalContent';
import { observer } from 'mobx-react-lite';
import { EntityPageWrapper } from './EntityPageWrapper';
import { EntityPageContextProvider } from '../../providers';
import { FieldValues, FormProvider } from 'react-hook-form';
import { minimalRequiredWdsRuntimeCheck } from '../../minimalRequiredWdsRuntimeCheck';
import { FormPageProvider } from '../FormPage';
import { ActionsBarConfig } from '@wix/bex-core';
import { useEntityPageLoadReporting } from './useEntityPageLoadReporting';

export interface EntityPageProps<T, V extends FieldValues = FieldValues>
  extends PageProps {
  /**
   * EntityPageState instance created with the `useEntityPage` hook
   */
  state: EntityPageState<T, V>;
  /**
   * Configuration for the actions bar
   */
  actionsBarConfig?: ActionsBarConfig;
}

function _EntityPage<T, V extends FieldValues = FieldValues>({
  state,
  actionsBarConfig,
  ...rest
}: EntityPageProps<T, V>) {
  if (process.env.NODE_ENV !== 'production') {
    minimalRequiredWdsRuntimeCheck({
      required: '^1.73.0',
      requiredBy: 'WixPatterns/EntityPage',
    });
  }

  useState(() => (state.actionsBarConfig = actionsBarConfig));

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

  const {
    bi: { startTime },
    _withinRouter,
    isFetching,
    initTask,
  } = state;

  useEntityPageLoadReporting({
    withinRouter: !!_withinRouter,
    startTime,
    isFetching,
    initTask,
  });

  return (
    <EntityPageContextProvider value={state}>
      <FormPageProvider state={state.formPage}>
        <FormProvider {...state.form}>
          <EntityPageWrapper state={state} {...rest} />
        </FormProvider>
      </FormPageProvider>
    </EntityPageContextProvider>
  );
}

_EntityPage.Header = EntityPageHeader;
_EntityPage.Content = EntityPageContent;
_EntityPage.MainContent = EntityPageMainContent;
_EntityPage.AdditionalContent = EntityPageAdditionalContent;
_EntityPage.Card = EntityPageCard;
_EntityPage.Slots = EntityPageSlots;
_EntityPage.Extensions = EntityPageSlots;

_EntityPage.displayName = 'EntityPage';

export const EntityPage = observer(_EntityPage);
