import React, { useState } from "react";
import { Pressable, PressableProps, StyleProp, ViewStyle } from "react-native";

import { useTheme } from "@/src/theme";

type Props = Omit<PressableProps, "style"> & { style?: StyleProp<ViewStyle>; focusScale?: number };

// Pressable with a clear focus ring for D-pad / remote control (Android TV, Fire TV) and press feedback.
export function Focusable({ style, focusScale = 1.06, children, onFocus, onBlur, ...rest }: Props) {
  const { colors } = useTheme();
  const [focused, setFocused] = useState(false);
  return (
    <Pressable
      {...rest}
      onFocus={(e) => {
        setFocused(true);
        onFocus?.(e);
      }}
      onBlur={(e) => {
        setFocused(false);
        onBlur?.(e);
      }}
      style={({ pressed }) => [
        { borderWidth: 2, borderColor: "transparent" },
        style,
        focused && { borderColor: colors.borderStrong, transform: [{ scale: focusScale }] },
        pressed && { opacity: 0.75, transform: [{ scale: 0.97 }] },
      ]}
    >
      {children}
    </Pressable>
  );
}
