import React, {FC} from 'react';
import {
  Pressable as RNPressable,
  PressableProps,
  StyleProp,
  ViewStyle,
} from 'react-native';
import {Pressable as GHPressable} from 'react-native-gesture-handler';
import {IconProps} from '@tabler/icons-react-native';
import {Pressable} from '@components/_core/Pressable';
import {ThemeAppearance, useTheme} from '@shared/theme';

import {ButtonSize, ButtonVariant} from '../../interfaces';
import {getColorsByVariant} from '../../utils';
import {styles} from './styles';

export interface IconButtonProps extends PressableProps {
  Icon: FC<IconProps>;
  onPress?: () => void;
  variant?: ButtonVariant;
  disabled?: boolean;
  style?: StyleProp<ViewStyle>;
  size?: ButtonSize;
  iconColor?: string;
  isFilledIcon?: boolean;
  appearance?: ThemeAppearance;
  backgroundColor?: string;
  onLongPress?: () => void;
  useGestureHandler?: boolean;
}

export function IconButton({
  Icon,
  onPress,
  disabled,
  style,
  iconColor,
  isFilledIcon,
  appearance = 'auto',
  size = 'lg',
  variant = 'primary',
  onLongPress,
  useGestureHandler,
  ...pressableProps
}: IconButtonProps) {
  const {theme, iconSizes} = useTheme();
  const {backgroundColor, textColor, borderColor, underlayColor} =
    getColorsByVariant({
      variant,
      disabled,
      appearance,
      theme,
    });
  const iconSize = size === 'lg' ? iconSizes.x6 : iconSizes.x4;
  const color =
    variant === 'tertiary' && !disabled
      ? theme.text.neutral.default
      : textColor;
  const PressableComponent = (
    useGestureHandler ? GHPressable : RNPressable
  ) as typeof RNPressable;

  return variant === 'flat' ? (
    <PressableComponent
      onPress={onPress}
      onLongPress={onLongPress}
      disabled={disabled}
      style={style}
      {...pressableProps}>
      <Icon size={iconSize} color={iconColor || color} />
    </PressableComponent>
  ) : (
    <Pressable
      onPress={onPress}
      onLongPress={onLongPress}
      backgroundColor={backgroundColor}
      underlayColor={underlayColor}
      disabled={disabled}
      style={[
        styles.container,
        styles[size],
        {borderColor},
        !!borderColor && styles.border,
        style,
      ]}
      useGestureHandler={useGestureHandler}
      {...pressableProps}>
      <Icon
        size={iconSize}
        {...(isFilledIcon
          ? {
              fill: iconColor || color,
              color: 'transparent',
            }
          : {color: iconColor || color})}
      />
    </Pressable>
  );
}
