import React, {memo} from 'react';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  withDelay,
} from 'react-native-reanimated';
import {BottomTabNavigationOptions} from '@react-navigation/bottom-tabs';
import {Pressable} from '@components/_core/Pressable';
import {Typography} from '@components/_core/Typography';
import {Badge} from '@components/_HuGo/Badge';
import {ICON_SIZES} from '@shared/theme';

import {SCALE_CONFIG, styles} from './styles';

interface TabBarButtonProps {
  isFocused: boolean;
  onPress: () => void;
  options: BottomTabNavigationOptions;
  selectedColor: string;
  buttonWidth: number;
}

function TabBarButtonComponent({
  isFocused,
  onPress,
  options,
  selectedColor,
  buttonWidth,
}: TabBarButtonProps) {
  const scale = useSharedValue(1);

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [{scale: scale.value}],
    };
  });

  const onPressIn = () => {
    scale.value = withSpring(1.1, SCALE_CONFIG);
  };

  const onPressOut = () => {
    scale.value = withDelay(200, withSpring(1, SCALE_CONFIG));
  };

  return (
    <Pressable
      accessibilityRole="button"
      accessibilityState={isFocused ? {selected: true} : {}}
      onPress={onPress}
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      style={[styles.container, {width: buttonWidth}]}>
      {options.tabBarIcon && (
        <Animated.View style={animatedStyle}>
          {options.tabBarIcon({
            focused: isFocused,
            color: selectedColor,
            size: ICON_SIZES.x6,
          })}
        </Animated.View>
      )}
      <Typography
        color={selectedColor}
        weight="semiBold"
        variant="xxxs"
        align="center"
        maxFontSizeMultiplier={1}
        numberOfLines={1}>
        {options.title}
      </Typography>
      {typeof options.tabBarBadge === 'number' && (
        <Badge show={options.tabBarBadge > 0} />
      )}
    </Pressable>
  );
}

export const TabBarButton = memo(TabBarButtonComponent);
