import { useState, use, createContext, useMemo, useLayoutEffect } from 'react';

type FullPageState = {
  inFullPage: boolean;
  showToggleButton: boolean;
  headerVisibleInFullPage: boolean;
  footerVisibleInFullPage: boolean;
  sidebarVisibleInFullPage: boolean;
};

type FullPageContextValue = FullPageState & {
  headerVisible: boolean;
  footerVisible: boolean;
  sidebarVisible: boolean;
  toggleFullPage: () => void;
  configure: (params: Partial<FullPageState>) => void;
};

export const FullPageContext = createContext<FullPageContextValue>(null!);

export const useFullPage = (initialState?: FullPageState) => {
  const ctx = use(FullPageContext);
  useLayoutEffect(() => {
    if (initialState) {
      ctx.configure(initialState);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return ctx;
};

export function FullPageProvider({ children = undefined, ...rest }: { children?: React.ReactNode }) {
  const [state, setState] = useState({
    inFullPage: false,
    showToggleButton: false,
    headerVisibleInFullPage: true,
    footerVisibleInFullPage: false,
    sidebarVisibleInFullPage: false,
  });
  const toggleFullPage = () => {
    setState((prev) => ({ ...prev, inFullPage: !prev.inFullPage }));
  };
  const value = useMemo<FullPageContextValue>(() => {
    return {
      ...state,
      headerVisible: !state.inFullPage || state.headerVisibleInFullPage,
      footerVisible: !state.inFullPage || state.footerVisibleInFullPage,
      sidebarVisible: !state.inFullPage || state.sidebarVisibleInFullPage,
      toggleFullPage,
      configure: (params) => setState((prev) => ({ ...prev, ...params })),
    };
  }, [state]);
  return (
    <FullPageContext value={value} {...rest}>
      {children}
    </FullPageContext>
  );
}
