import React, { useRef } from "react";
import {
  View,
  TouchableOpacity,
  ViewStyle,
  TextStyle,
  Text,
  Platform,
} from "react-native";
import { FocusableGroup } from "@applicaster/zapp-react-native-ui-components/Components/FocusableGroup";
import { Focusable } from "@applicaster/zapp-react-native-ui-components/Components/Focusable";
import { focusManager } from "@applicaster/zapp-react-native-utils/focusManager/FocusManager";
type Props = {
  styles: {
    button: ViewStyle;
    focusedButton: ViewStyle;
    buttonText: TextStyle;
    focusedText: TextStyle;
  };
  onPress: () => void;
  text: string;
};

export function ButtonTV(props: Props) {
  const buttonRef = useRef(null);

  const renderButton = (focused) => {
    return (
      <TouchableOpacity
        onPress={() => {
          props?.onPress?.();
        }}
        activeOpacity={1}
        style={[
          props?.styles?.button,
          focused ? props?.styles?.focusedButton : {},
        ]}
      >
        <Text
          style={[
            props?.styles.buttonText,
            focused ? props?.styles?.focusedText : {},
          ]}
        >
          {props?.text}
        </Text>
      </TouchableOpacity>
    );
  };

  const focusableGroupId = "error_screen_button_group";
  const focusableId = "error_screen_button";

  React.useEffect(() => {
    if (buttonRef.current) {
      focusManager.setFocus(buttonRef);
    }
  }, [buttonRef.current]);

  return Platform.OS !== "android" ? (
    <FocusableGroup id={focusableGroupId}>
      <Focusable
        id={focusableId}
        groupId={focusableGroupId}
        onPress={() => props?.onPress?.()}
      >
        {(focused) => renderButton(focused)}
      </Focusable>
    </FocusableGroup>
  ) : (
    <View>
      <Focusable
        ref={buttonRef}
        id={focusableId}
        groupId={"storefront-general-content"}
        preferredFocus={true}
        onPress={() => {
          props?.onPress?.();
        }}
      >
        {(focused) => renderButton(focused)}
      </Focusable>
    </View>
  );
}
