import * as React from "react";
import { pathOr } from "ramda";

import { usePickFromState } from "@applicaster/zapp-react-native-redux/hooks";

import { ScreenLayoutContextProvider } from "./ScreenLayoutContextProvider";
import { StackNavigator } from "../../Navigator";
import { getBackgroundImageUrl } from "../utils";
import { useTheme } from "@applicaster/zapp-react-native-utils/theme";

type Components = {
  NavBar: React.ComponentType<any>;
  Background: React.ComponentType<any>;
};

type Props = {
  Components: Components;
};

const Layout = ({ Components }: Props) => {
  const { appState, remoteConfigurations } = usePickFromState([
    "appState",
    "remoteConfigurations",
  ]);

  const appReady = pathOr(false, ["appReady"], appState);

  const theme = useTheme();

  const backgroundColor = React.useMemo(() => theme.app_background_color, []);

  const backgroundImageUrl = React.useMemo(
    () => getBackgroundImageUrl(remoteConfigurations),
    [remoteConfigurations]
  );

  if (!appReady) {
    return null;
  }

  return (
    <ScreenLayoutContextProvider>
      <Components.Background
        backgroundColor={backgroundColor}
        backgroundImageUrl={backgroundImageUrl}
      >
        <StackNavigator Components={Components} />
      </Components.Background>
    </ScreenLayoutContextProvider>
  );
};

export default Layout;
