import React, {memo} from 'react';
import {View} from 'react-native';
import {BottomTabBarProps} from '@react-navigation/bottom-tabs';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {NewThemeColors, ThemeColors} from '@shared/theme';

import {getTabBarButtonWidth, getTabbarStyles} from './styles';
import {TabBarButton} from './components/TabBarButton';

interface TabbarProps extends BottomTabBarProps {
  theme: ThemeColors & NewThemeColors;
}

//TODO: Pending colors token migration
function BottomTabBarComponent({
  state,
  descriptors,
  navigation,
  theme,
}: TabbarProps) {
  const {bottom} = useSafeAreaInsets();
  const styles = getTabbarStyles(theme, bottom);
  const buttonWidth = getTabBarButtonWidth(state.routes.length);

  return (
    <View style={styles.container}>
      {state.routes.map((route, index) => {
        const {options} = descriptors[route.key];
        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
            canPreventDefault: true,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name, route.params);
          }
        };

        const selectedColor = isFocused
          ? theme.button.background.primary.default
          : theme.text.neutral.lighter;

        return (
          <TabBarButton
            key={route.key}
            isFocused={isFocused}
            onPress={onPress}
            options={options}
            selectedColor={selectedColor}
            buttonWidth={buttonWidth}
          />
        );
      })}
    </View>
  );
}

export const BottomTabBar = memo(BottomTabBarComponent);
