import * as React from "react";
import { ListRenderItemInfo as IListRenderItemInfo } from "react-native";
import { FocusableItem } from "./FocusableItem";

export type IListRenderItem<ItemT> = (
  info: IListRenderItemInfo<ItemT> & {
    focused: boolean;
    onLoadFinished: () => void;
    onLoadFailed: () => void;
  }
) => React.ReactElement | null;

type Item = ZappEntry | ZappUIComponent | any;

type Props = {
  item: Item;
  onFocus: (
    element: FocusManager.FocusableRef,
    renderArgs: { item: Item; index: number },
    direction: FocusManager.Android.FocusNavigationDirections
  ) => void;
  onListElementBlur?: (any, RenderItemProps, Direction) => void;
  onListElementPress?: (any, RenderItemProps) => void;
  onListElementLongPress?: (any, RenderItemProps) => void;
  onListElementPressOut?: (any, RenderItemProps) => void;
  focusableItemProps: any;
  id: string;
  index: number;
  extraData: any;
  extraChildrenData: any;
  renderItem: IListRenderItem<any> | null | undefined;
  getNextFocus: (index: number) => ParentFocus;
} & ParentFocus;

export const FocusableListItemWrapper = React.memo(
  ({
    onFocus,
    onListElementBlur,
    onListElementPress,
    onListElementLongPress,
    onListElementPressOut,
    focusableItemProps,
    id,
    getNextFocus,
    item,
    index,
    extraData,
    extraChildrenData,
    renderItem,
  }: Props) => {
    const nextFocus = getNextFocus(index);

    return (
      <FocusableItem
        nextFocusDown={nextFocus.nextFocusDown}
        nextFocusRight={nextFocus.nextFocusRight}
        nextFocusLeft={nextFocus.nextFocusLeft}
        nextFocusUp={nextFocus.nextFocusUp}
        id={id}
        focusableItemProps={focusableItemProps}
        onFocus={onFocus}
        item={item}
        index={index}
        renderItem={renderItem}
        extraChildrenData={extraChildrenData}
        extraData={extraData}
        onListElementBlur={onListElementBlur}
        onListElementPress={onListElementPress}
        onListElementLongPress={onListElementLongPress}
        onListElementPressOut={onListElementPressOut}
      />
    );
  }
);

FocusableListItemWrapper.displayName = "FocusableListItemWrapper";
