import { NavigationContainer } from "@react-navigation/native";
import { StoreProvider } from "easy-peasy";
import React, { useMemo } from "react";
import { QueryClientProvider } from "react-query";

import { getQueryClient } from "mazlo-api";

import { View } from "../../components/View";
import { setTopLevelNavigator } from "../../services/Router";
import { getOrCreateStore } from "../../services/store";
import { AppProps } from "./";

const App = ({
  children,
  initialStore = {},
  navigationProps = {},
}: AppProps) => {
  const store = useMemo(() => getOrCreateStore(initialStore), [initialStore]);

  return (
    <StoreProvider store={store}>
      <QueryClientProvider client={getQueryClient()}>
        <NavigationContainer
          {...navigationProps}
          ref={(navigatorRef) => {
            setTopLevelNavigator(navigatorRef);
          }}
        >
          {children}
          <View
            nativeID="portal"
            style={{ position: "absolute", top: 0, left: 0, zIndex: 10000 }}
          />
        </NavigationContainer>
      </QueryClientProvider>
    </StoreProvider>
  );
};

export default App;
