import React, {useState, useCallback} from 'react';
import {
  TouchableOpacity as RNTouchableOpacity,
  TouchableOpacityProps,
} from 'react-native';
import {IS_TV, TV_FOCUS_COLOR, TV_FOCUS_BORDER} from '../../utils/tv';

/**
 * Drop-in replacement for RN's TouchableOpacity.
 * When IS_TV is true and `focusable` is set, automatically shows a cyan
 * focus border on D-pad focus. Otherwise behaves identically to stock.
 */
export function TVTouchable(props: TouchableOpacityProps) {
  const {style, onFocus, onBlur, focusable, ...rest} = props;
  const [focused, setFocused] = useState(false);

  const handleFocus = useCallback(
    (e: any) => {
      setFocused(true);
      onFocus?.(e);
    },
    [onFocus],
  );

  const handleBlur = useCallback(
    (e: any) => {
      setFocused(false);
      onBlur?.(e);
    },
    [onBlur],
  );

  const showTVFocus = IS_TV && !!focusable;

  return (
    <RNTouchableOpacity
      focusable={focusable}
      onFocus={showTVFocus ? handleFocus : onFocus}
      onBlur={showTVFocus ? handleBlur : onBlur}
      style={
        showTVFocus && focused
          ? [style, {borderWidth: TV_FOCUS_BORDER, borderColor: TV_FOCUS_COLOR}]
          : style
      }
      {...rest}
    />
  );
}
