import * as React from "react";
import { View, StyleSheet } from "react-native";

import { DimensionsContext } from "./DimensionsContext";

type Props = {
  children: React.ReactNode;
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

const DimensionsProviderComponent: React.FunctionComponent = ({
  children,
}: Props) => {
  const [dimensions, setDimension] = React.useState({
    width: null,
    height: null,
  });

  const [dimensionsReady, setDimensionsReady] = React.useState(false);

  const onLayout = React.useCallback(
    ({
      nativeEvent: {
        layout: { width, height },
      },
    }) => {
      if (!dimensionsReady) {
        setDimensionsReady(true);
      }

      if (dimensions.width !== width || dimensions.height !== height) {
        setDimension({ width, height });
      }
    },
    [dimensionsReady, dimensions.width, dimensions.height]
  );

  const display = React.useMemo(
    () => (dimensionsReady ? "flex" : "none"),
    [dimensionsReady]
  );

  return (
    <DimensionsContext.Provider
      value={{
        width: dimensions.width,
        height: dimensions.height,
      }}
    >
      <View
        testID="on-layout-view"
        style={styles.container}
        onLayout={onLayout}
      >
        <View style={{ ...styles.container, display }}>{children}</View>
      </View>
    </DimensionsContext.Provider>
  );
};

export const DimensionsProvider = React.memo<Props>(
  DimensionsProviderComponent
);
