import * as React from "react";

import { usePickFromState } from "@applicaster/zapp-react-native-redux/hooks";
import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils";
import { usePathname } from "@applicaster/zapp-react-native-utils/reactHooks/navigation";

type Props = ZappUIComponentProps & {
  rivers: ZappRivers;
  screenId: string;
  screenData?: ZappRivers;
};

export function withRiver(Component: ZappComponent): ZappComponent {
  const RiverWithData = ({ screenId, ...otherProps }: Props) => {
    const { rivers } = usePickFromState(["rivers"]);
    const pathname = usePathname();
    const river = rivers[screenId];

    if (!river) {
      return null;
    }

    if (!otherProps.screenData) {
      otherProps.screenData = river;
    }

    return (
      <Component
        screenId={screenId}
        river={river}
        key={isTV() ? pathname : undefined}
        {...otherProps}
      />
    );
  };

  return RiverWithData;
}
