import React, {memo, useState} from 'react';
import {ScrollView} from 'react-native';
import {
  RNTabBarProps,
  TabBarProps,
  TabViewRoute,
} from '@components/TabView/interfaces';
import {Badge, Chip} from '@components/_HuGo';

import {styles} from './styles';

function TabBarPills<T extends TabViewRoute>({
  style,
  handleTabPress,
  navigationState,
  jumpTo,
  size,
  ...rest
}: TabBarProps<T> & RNTabBarProps) {
  const {key: selectedTab, module: selectedModule} =
    navigationState.routes[navigationState.index];

  const [innerSelectedTab, setInnerSelectedTab] = useState(selectedTab);

  const handlePress = (key: string) => () => {
    jumpTo(key);
    setInnerSelectedTab(key);
    handleTabPress?.(key, selectedTab, selectedModule);
  };

  return (
    <ScrollView
      style={[styles.container, style]}
      contentContainerStyle={styles.innerContainer}
      showsHorizontalScrollIndicator={false}
      horizontal>
      {navigationState.routes.map(route => (
        <Chip
          key={route.key}
          active={route.key === innerSelectedTab}
          text={route.title}
          onPress={handlePress(route.key)}
          size={size}
          showActiveIcon={false}
          showCloseIcon={false}
          RightIcon={
            route.badge ? (
              <Badge show={!!route.badge} value={route.badge} />
            ) : undefined
          }
          {...rest}
        />
      ))}
    </ScrollView>
  );
}

export default memo(TabBarPills);
