//@ts-nocheck
import React, { useEffect, useState } from 'react';
import {
  Keyboard,
  LayoutAnimation,
  View,
  Dimensions,
  Platform,
  StyleSheet,
  ViewStyle,
  KeyboardEvent,
} from 'react-native';

type Props = {
  topSpacing?: number;
  onToggle?: (isOpen: boolean, height: number) => void;
  style?: ViewStyle;
};

const styles = StyleSheet.create({
  container: {
    left: 0,
    right: 0,
  },
});

const defaultAnimation = {
  duration: 500,
  create: {
    duration: 300,
    type: LayoutAnimation.Types.easeInEaseOut,
    property: LayoutAnimation.Properties.opacity,
  },
  update: {
    type: LayoutAnimation.Types.spring,
    springDamping: 200,
  },
};

const KeyboardSpacer: React.FC<Props> = ({
  topSpacing = 0,
  onToggle = () => {},
  style,
}) => {
  const [keyboardSpace, setKeyboardSpace] = useState(0);

  useEffect(() => {
    const showEvent =
      Platform.OS === 'android' ? 'keyboardDidShow' : 'keyboardWillShow';
    const hideEvent =
      Platform.OS === 'android' ? 'keyboardDidHide' : 'keyboardWillHide';

    const onShow = (event: KeyboardEvent) => {
      if (!event?.endCoordinates) return;

      let animationConfig = defaultAnimation;

      if (Platform.OS === 'ios') {
        animationConfig = LayoutAnimation.create(
          event.duration,
          LayoutAnimation.Types[event.easing] || 'keyboard',
          LayoutAnimation.Properties.opacity
        );
      }

      LayoutAnimation.configureNext(animationConfig);

      const screenHeight = Dimensions.get('window').height;
      const height = screenHeight - event.endCoordinates.screenY + topSpacing;

      setKeyboardSpace(height);
      onToggle(true, height);
    };

    const onHide = (event: KeyboardEvent) => {
      let animationConfig = defaultAnimation;

      if (Platform.OS === 'ios') {
        animationConfig = LayoutAnimation.create(
          event?.duration || 250,
          LayoutAnimation.Types[event?.easing] || 'keyboard',
          LayoutAnimation.Properties.opacity
        );
      }

      LayoutAnimation.configureNext(animationConfig);

      setKeyboardSpace(0);
      onToggle(false, 0);
    };

    const showSub = Keyboard.addListener(showEvent, onShow);
    const hideSub = Keyboard.addListener(hideEvent, onHide);

    return () => {
      showSub.remove();
      hideSub.remove();
    };
  }, [topSpacing, onToggle]);

  return <View style={[styles.container, { height: keyboardSpace }, style]} />;
};

export default KeyboardSpacer;
