import * as React from "react";
import { Focusable } from "../Focusable/index.android";
import { FocusableChild } from "./FocusableChild";
import { noop } from "@applicaster/zapp-react-native-utils/functionUtils";
import { IListRenderItem } from "./index";

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

const FocusableItemComponent = ({
  item,
  index,
  onFocus,
  onListElementBlur,
  onListElementPress,
  onListElementLongPress,
  onListElementPressOut,
  focusableItemProps,
  id,
  nextFocusDown,
  nextFocusRight,
  nextFocusLeft,
  nextFocusUp,
  extraData,
  renderItem,
  extraChildrenData,
}: FocusableItemComponentProps) => {
  const renderArgs = { item, index };

  const onFocusHandler = React.useCallback(
    (element, direction) => {
      onFocus?.(element, renderArgs, direction);
    },
    [item, onFocus]
  );

  const onBlurHandler = React.useCallback(
    (element, direction) => {
      onListElementBlur?.(element, renderArgs, direction);
    },
    [item, onListElementBlur]
  );

  const onPressHandler = React.useCallback(
    (element) => {
      onListElementPress?.(element, renderArgs);
    },
    [item, onListElementPress]
  );

  const onLongPressHandler = React.useCallback(
    (element) => {
      onListElementLongPress?.(element, renderArgs);
    },
    [item, onListElementLongPress]
  );

  const onPressOutHandler = React.useCallback(
    (element) => {
      onListElementPressOut?.(element, renderArgs);
    },
    [item, onListElementPressOut]
  );

  return (
    <Focusable
      nextFocusDown={nextFocusDown}
      nextFocusRight={nextFocusRight}
      nextFocusLeft={nextFocusLeft}
      nextFocusUp={nextFocusUp}
      onFocus={onFocusHandler}
      onBlur={onBlurHandler}
      onPress={onPressHandler}
      onLongPress={onLongPressHandler}
      onPressOut={onPressOutHandler}
      id={id}
      {...focusableItemProps}
    >
      <FocusableChild
        id={id}
        item={item}
        index={index}
        parentRef={null}
        renderItem={renderItem}
        extraChildrenData={extraChildrenData}
        extraData={extraData}
        onLoadFinished={noop}
      />
    </Focusable>
  );
};

export const FocusableItem = React.memo(FocusableItemComponent);
