import React from 'react';
import _ from 'lodash';
import {SCAN} from '@constants/navigation/app-bottom-tab';
import {
  Container,
  Tab,
  Title,
  IconWrapper,
  Highlighter,
} from '@styles/components/app-bottom-tab';

const AppBottomTab = ({state, descriptors, navigation}: any) => (
  <Container>
    {state.routes.map((route: {name: string; key: string}, index: any) => {
      const {options} = descriptors[route.key];
      const label =
        options.tabBarLabel !== undefined
          ? options.tabBarLabel
          : options.title !== undefined
          ? options.title
          : route.name;

      const isFocused = state.index === index;

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

        if (!isFocused && !event.defaultPrevented) {
          // The `merge: true` option makes sure that the params inside the tab screen are preserved
          navigation.navigate({name: route.name, merge: true});
        }
      };

      const onLongPress = () => {
        navigation.emit({
          type: 'tabLongPress',
          target: route.key,
        });
      };

      const Icon = _.isFunction(options?.tabBarIcon)
        ? options?.tabBarIcon()
        : null;

      const isScan = route.name === SCAN.SCREEN;

      return (
        <Tab
          key={route.key}
          accessibilityRole="button"
          accessibilityState={isFocused ? {selected: true} : {}}
          accessibilityLabel={options.tabBarAccessibilityLabel}
          testID={options.tabBarTestID}
          onPress={onPress}
          onLongPress={onLongPress}>
          {isFocused && <Highlighter />}
          {Icon && (
            <IconWrapper isScan={isScan}>
              <Icon fill={isFocused ? '#2BEAFB' : '#4F58CF'} />
            </IconWrapper>
          )}
          <Title isFocused={isFocused} isScan={isScan} testID="btmBarBtn">
            {label}
          </Title>
        </Tab>
      );
    })}
  </Container>
);

export default AppBottomTab;
