import React, { memo, useCallback } from "react";
import { requireNativeComponent, View } from "react-native";
import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils";
const TrackedViewComponent: any = requireNativeComponent("TrackedView");

type TrackedViewNativeProps = {
  nativeEvent: { rect?: Record<string, number> };
};

type TrackedViewProps = {
  children?: React.ReactNode;
  onPositionUpdated: (props: { rect?: Record<string, number> }) => void;
  testId?: string | undefined;
  groupId?: string;
};

export const TrackedView = memo(function TrackedView(props: TrackedViewProps) {
  const children = props.children;

  const onPositionUpdated = useCallback(
    (event: TrackedViewNativeProps) => {
      props.onPositionUpdated(event.nativeEvent);
    },
    [props.onPositionUpdated]
  );

  if (isTV()) {
    return <View {...(props as any)}>{children}</View>;
  }

  return (
    <TrackedViewComponent {...props} onPositionUpdated={onPositionUpdated}>
      {children}
    </TrackedViewComponent>
  );
});
