import * as React from 'react'
import type { ComponentType } from 'react'
import {
  Image,
  type ImageStyle,
  type StyleProp,
  TouchableOpacity,
  type TouchableOpacityProps,
  View,
  type ViewStyle,
} from 'react-native'
import { iconRegistry } from './iconRegistry'

export type Icon3DTypes = keyof typeof iconRegistry

export interface Icon3DProps extends TouchableOpacityProps {
  /**
   * The name of the icon
   */
  icon: Icon3DTypes
  /**
   * An optional size for the icon. If not provided, the icon will be sized to the icon's resolution.
   */
  size?: number

  /**
   * Style overrides for the icon image
   */
  style?: StyleProp<ImageStyle>

  /**
   * Style overrides for the icon container
   */
  containerStyle?: StyleProp<ViewStyle>

  /**
   * An optional function to be called when the icon is pressed
   */
  onPress?: TouchableOpacityProps['onPress']
}

/**
 * A component to render a registered icon.
 * It is wrapped in a <TouchableOpacity /> if `onPress` is provided, otherwise a <View />.
 */
export const Icon3D = (props: Icon3DProps) => {
  const {
    icon,
    size = 24,
    style: $imageStyleOverride,
    containerStyle: $containerStyleOverride,
    ...WrapperProps
  } = props
  const isPressable = !!WrapperProps.onPress

  // @ts-ignore
  const Wrapper: ComponentType<TouchableOpacityProps> = WrapperProps?.onPress
    ? TouchableOpacity
    : View

  return (
    <Wrapper
      accessibilityRole={isPressable ? 'imagebutton' : undefined}
      {...WrapperProps}
      style={$containerStyleOverride}
    >
      <Image
        style={[$imageStyle, { width: size, height: size }, $imageStyleOverride]}
        source={iconRegistry[icon]}
      />
    </Wrapper>
  )
}

const $imageStyle: ImageStyle = {
  resizeMode: 'contain',
}
