import {createContext, PropsWithChildren, useContext} from 'react';
import {useReanimatedKeyboardAnimation} from 'react-native-keyboard-controller';
import {AnimatedStyle, useAnimatedStyle} from 'react-native-reanimated';
import {useSafeAreaInsets} from 'react-native-safe-area-context';

const KeyboardOffsetStyleContext = createContext<AnimatedStyle>({});

export function KeyboardOffsetStyleProvider({children}: PropsWithChildren) {
  const {height} = useReanimatedKeyboardAnimation();
  const {bottom} = useSafeAreaInsets();

  const offsetStyle = useAnimatedStyle(() => {
    return {
      transform: [{translateY: Math.min(height.value + bottom, 0)}],
    };
  }, []);

  // Currently share the offset style via context
  return (
    <KeyboardOffsetStyleContext.Provider value={offsetStyle}>
      {children}
    </KeyboardOffsetStyleContext.Provider>
  );
}

export const useKeyboardOffsetStyleContext = () => {
  return useContext(KeyboardOffsetStyleContext);
};
