import * as React from "react";
import { FocusableGroupNative } from "@applicaster/zapp-react-native-ui-components/Components/NativeFocusables";
import { BaseFocusable } from "@applicaster/zapp-react-native-ui-components/Components/BaseFocusable";
import { createLogger } from "@applicaster/zapp-react-native-utils/logger";

const { log_verbose } = createLogger({
  subsystem: "General",
  category: "FocusableGroup",
});

type FocusableGroupNativeEvent = {
  nativeEvent: {
    focusHeading: FocusManager.Direction;
    groupId: string;
    isActive: boolean;
    isFocusDisabled: boolean;
    isFocusingByUser: boolean;
    itemId: string;
    target: number;
  };
};

type Props = {
  id: string;
  children: React.ReactNode;
  isFocusDisabled: boolean;
  isWithMemory: boolean;
  focusGroupRef: React.Component;
  shouldUsePreferredFocus: boolean;
  groupId: string;
  preferredFocus: boolean;
  style: Record<any, any>;
  screenData: { screenId: string; parentScreenId: string };
};

export class FocusableGroup extends BaseFocusable<Props> {
  public readonly isGroup: boolean = true;

  render() {
    const {
      children,
      id,
      isFocusDisabled,
      isWithMemory,
      style = {},
      groupId,
      ...otherProps
    } = this.props;

    const onGroupFocus = ({ nativeEvent }: FocusableGroupNativeEvent) => {
      log_verbose("FOCUSABLE_GROUP: onGroupFocus", { nativeEvent });
      this.onFocus(this.ref, nativeEvent.focusHeading);
    };

    const onGroupBlur = ({ nativeEvent }: FocusableGroupNativeEvent) => {
      log_verbose("FOCUSABLE_GROUP: onGroupBlur", { nativeEvent });
      this.onBlur(this.ref, nativeEvent.focusHeading);
    };

    return (
      <FocusableGroupNative
        groupId={`${groupId}`}
        itemId={id}
        ref={this.ref}
        isFocusDisabled={isFocusDisabled}
        isWithMemory={isWithMemory}
        onGroupFocus={onGroupFocus}
        onGroupBlur={onGroupBlur}
        style={style}
        {...otherProps}
      >
        {children}
      </FocusableGroupNative>
    );
  }
}
