// External imports.
import * as React from 'react';
import { StyleSheet, View } from 'react-native';
import { withTheme, TouchableRipple } from 'react-native-paper';
import tinyColor from 'tinycolor2';

// Types imports.
import type { PropsWithTheme, Props } from './IconButton.types';

// Internal imports.
import styles from './IconButton.styles';
import Icon from './Icon';
import ResponsiveDimensions from '../../utils/ResponsiveDimensions';

/**
 * IconButton component (unwrapped, for testing)
 * Renders an icon button with ripple effect
 * @internal For testing purposes only. Do not use in production code.
 */
export const IconButtonComponent = React.memo(
  (props: PropsWithTheme): React.ReactElement => {
    const {
      image,
      vector,
      iconName,
      size,
      color,
      onPress,
      onLongPress,
      onPressIn,
      onPressOut,
      disabled,
      iconPercent,
      style,
      theme,
      noIconTint,
      ...other
    } = props;

    const _size: number = ResponsiveDimensions.ms(size ?? 36);
    const _color: string = color ?? theme.colors.primary;
    const _enabledStyle = { opacity: disabled ? 0.5 : 1.0 };
    const _rippleColor = tinyColor(_color).setAlpha(0.25).toHex8String();

    return (
      <View
        style={StyleSheet.flatten([
          styles.container,
          { borderRadius: _size / 2 },
          style,
          { width: _size, height: _size },
          _enabledStyle,
          styles.noPadding,
        ])}
        {...other}
      >
        <TouchableRipple
          style={styles.ripple}
          onPress={onPress}
          onLongPress={onLongPress}
          onPressIn={onPressIn}
          onPressOut={onPressOut}
          disabled={disabled}
          rippleColor={_rippleColor}
          underlayColor={_rippleColor}
        >
          <View style={StyleSheet.flatten([styles.ripple, styles.rippleView])}>
            <Icon
              image={image}
              vector={vector}
              iconName={iconName}
              size={_size}
              color={_color}
              iconPercent={iconPercent}
              noIconTint={noIconTint}
            />
          </View>
        </TouchableRipple>
      </View>
    );
  }
);

IconButtonComponent.displayName = 'IconButtonComponent';

/**
 * IconButton component (wrapped with theme, for production)
 */
const IconButton = withTheme(IconButtonComponent) as React.ComponentType<Props>;

export default IconButton;
