import React, { createContext, useEffect, useState } from "react";
import { useWindowDimensions, ScaledSize, Platform } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const defaultDimensions = {
  scale: 1,
  fontScale: 1,
  height: 1,
  width: 1,
};

export const DimensionsContext = createContext<ScaledSize>(defaultDimensions);

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

export default function DimensionsProvider({ children }: Props) {
  const dimensions = useWindowDimensions();
  const insets = useSafeAreaInsets();

  // We have to use defaults on initial render because for web the
  // initial render (SSR or SSG) doesn't know the screen size and
  // will cause render mismatches.
  const [safeDimensions, setSafeDimensions] = useState<ScaledSize>(
    Platform.OS === "web"
      ? defaultDimensions
      : {
          ...dimensions,
          width: dimensions.width - insets.left - insets.right,
          height: dimensions.height = insets.top - insets.bottom,
        }
  );

  useEffect(() => {
    setSafeDimensions({
      ...dimensions,
      width: dimensions.width - insets.left - insets.right,
      height: dimensions.height = insets.top - insets.bottom,
    });
  }, [dimensions, insets]);

  return (
    <DimensionsContext.Provider value={safeDimensions}>
      {children}
    </DimensionsContext.Provider>
  );
}
