import {Link as ExpoLink, type Href} from 'expo-router'
import {type ReactNode} from 'react'
import {
  Pressable,
  StyleSheet,
  type PressableProps,
} from 'react-native'

import {useInteractionState} from '@/hooks/use-interaction-state'
import {pressed, type ViewStyleProp} from '@/sprinkles'

type LinkProps = {
  href: Href
  children?: ReactNode | ((pressed: boolean) => ReactNode)
  style?: ViewStyleProp
  hitSlop?: PressableProps['hitSlop']
  onLongPress?: PressableProps['onLongPress']
  accessibilityLabel?: string
  accessibilityHint?: string
}

export function Link({
  href,
  children,
  style,
  hitSlop,
  onLongPress,
  accessibilityLabel,
  accessibilityHint,
}: LinkProps) {
  const {state: isPressed, onIn, onOut} = useInteractionState()
  const isRenderProp = typeof children === 'function'
  return (
    <ExpoLink href={href} asChild>
      <Pressable
        accessibilityRole="link"
        accessibilityLabel={accessibilityLabel}
        accessibilityHint={accessibilityHint}
        hitSlop={hitSlop}
        onLongPress={onLongPress}
        onPressIn={onIn}
        onPressOut={onOut}
        style={StyleSheet.flatten([
          !isRenderProp && isPressed && pressed,
          style,
        ])}
      >
        {isRenderProp ? children(isPressed) : children}
      </Pressable>
    </ExpoLink>
  )
}
