import React from "react";
import { Animated, ViewProps, ViewStyle } from "react-native";
import { useSafeAreaFrame } from "react-native-safe-area-context";

import { useScreenOrientationHandler } from "@applicaster/zapp-react-native-ui-components/Components/Screen/orientationHandler";

import { PathnameContext } from "../../Contexts/PathnameContext";
import { ScreenDataContext } from "../../Contexts/ScreenDataContext";
import { ScreenContextProvider } from "../../Contexts/ScreenContext";

type Props = {
  children: any;
  style: any;
  pointerEvents: ViewProps["pointerEvents"];
  overlayStyle: ViewStyle;
  animating: boolean;
  contentStyle: ViewStyle;
  pathname: string;
  isActive: boolean;
  screenData: NavigationScreenData;
};

/**
 * Animated View container for any purpose.
 * Renders given children with given style object.
 * Optional property: pointer event (e.g. to prevent interaction with animating scene).
 * @param {React.Component} children Just about anything
 * @param {object} style             Container style
 * @param {} pointerEvents           box-none|none|box-only|auto (default)
 * @param overlayStyle
 * @param animating
 * @param contentStyle
 * @param screenUniqueId
 */
export function Scene({
  children,
  style,
  pointerEvents = "auto",
  overlayStyle,
  animating,
  contentStyle,
  pathname,
  isActive = false,
  screenData,
}: Props) {
  const [initialScreenData, setInitialScreenData] = React.useState(screenData);

  useScreenOrientationHandler({
    screenData,
    isActive,
  });

  React.useLayoutEffect(() => {
    if (isActive) {
      setInitialScreenData(screenData);
    }
  }, [screenData, isActive]);

  const frame = useSafeAreaFrame();
  const isAnimating = animating && overlayStyle;

  const dimensions = isAnimating
    ? {
        width: "100%",
        height: "100%",
      }
    : frame;

  return (
    <Animated.View
      pointerEvents={pointerEvents}
      style={[style, contentStyle, dimensions]}
    >
      <ScreenDataContext.Provider value={initialScreenData}>
        <PathnameContext.Provider value={pathname}>
          <ScreenContextProvider pathname={pathname}>
            {children}
          </ScreenContextProvider>
        </PathnameContext.Provider>
      </ScreenDataContext.Provider>
      {isAnimating && <Animated.View style={overlayStyle} />}
    </Animated.View>
  );
}
