import React, { useEffect, useRef } from "react";
import { findNodeHandle } from "react-native";

import { View, useKeypressed } from "mazlo-ui";
type Props = {
  children: React.ReactNode;
  flex?: boolean;
  onEnter?: () => void;
};

const EnterHandler = React.forwardRef<any, Props>(
  ({ onEnter, children, flex, ...props }, ref) => {
    const node = useRef();
    const currentNode = findNodeHandle(node.current) as any;
    const enterPressed = useKeypressed("Enter", currentNode);
    useEffect(() => {
      if (onEnter && enterPressed) {
        onEnter();
      }
    }, [onEnter, enterPressed, node.current]);
    return (
      <View ref={node} flex={flex} {...props}>
        <View ref={ref} flex={flex}>
          {children}
        </View>
      </View>
    );
  }
);

export default EnterHandler;
