import React, { ReactNode, useMemo, useState } from 'react';
import { useReactive } from '@wix/bex-utils/react';
import {
  PageContextProvider,
  useWixPatternsContainer,
} from '@wix/bex-core/react';
import { PageState, SidePanelWidth } from '@wix/bex-core';
import { runInAction } from 'mobx';
import { WixDesignSystemProvider } from '@wix/design-system';

export interface PageWrapperBaseProps {
  pageState?: PageState;
  children?: ReactNode;
}

export function PageWrapperBase(props: PageWrapperBaseProps) {
  const { pageState, children } = props;

  const [state] = useState(() => pageState ?? new PageState());
  const { modalsContainerRef, stackingRootRef, _sidePanelOpen } = state;
  const sidePanelOpen = useReactive(_sidePanelOpen);
  const { environment, useRelativeSidePanel, isMobile } =
    useWixPatternsContainer();

  const pageAndModalsRootStyle = useMemo(
    () => ({
      position: 'relative' as const,
      width: sidePanelOpen ? `calc(100% - ${SidePanelWidth}px)` : '100%',
      height: '100%',
      transition: 'width 0.4s ease 0s',
      zIndex: 1,
    }),
    [sidePanelOpen],
  );

  const rootStyle = useMemo(
    () => ({
      position: 'relative' as const,
      width: '100%',
      height: '100%',
      overflow: useRelativeSidePanel ? ('hidden' as const) : undefined,
    }),
    [],
  );

  const modalsContainerStyle = useMemo(
    () => ({
      position: 'absolute' as const,
      zIndex: 1,
    }),
    [],
  );

  let child = (
    <PageContextProvider value={state}>
      <div
        data-wix-patterns
        style={rootStyle}
        data-hook="cairo-root-stacking"
        ref={(el) => {
          stackingRootRef.current = el;
        }}
        lang={environment.language}
      >
        <div style={pageAndModalsRootStyle}>{children}</div>
        <div
          data-hook="modals-container"
          ref={(el) => {
            runInAction(() => {
              modalsContainerRef.current = el;
            });
          }}
          style={modalsContainerStyle}
        />
      </div>
    </PageContextProvider>
  );

  if (isMobile) {
    child = (
      <WixDesignSystemProvider mobile={true}>{child}</WixDesignSystemProvider>
    );
  }

  return child;
}
