import React, { useState } from 'react';
import { View, Pressable } from 'react-native';
import { theme } from '../theme';
import { getTabbarHeight } from '../../common/transducers';
import { BottomTabButton } from '../components/bottom-tab-button';
import { TTabButton } from '../types';

const TabButton = ({
  isFocused,
  options,
  route,
  onPress,
  onLongPress,
}: TTabButton) => {
  const [pressed, setPressed] = useState(false);

  return (
    <Pressable
      accessibilityRole="button"
      accessibilityState={isFocused ? { selected: true } : {}}
      accessibilityLabel={options.tabBarAccessibilityLabel}
      // testID={options.tabBarTestID}
      testID={route.name}
      onPress={onPress}
      onLongPress={onLongPress}
      style={{ flex: 1 }}
      key={route.name}
      onPressIn={() => setPressed(true)}
      onPressOut={() => setPressed(false)}
    >
      <BottomTabButton
        pressed={pressed}
        focused={isFocused}
        routeName={route.name}
      />
    </Pressable>
  );
};

export function TabBarCustom({ state, descriptors, navigation }: any) {
  const focusedOptions = descriptors[state.routes[state.index].key].options;

  if (focusedOptions.tabBarVisible === false) {
    return null;
  }

  return (
    <View
      style={{
        flexDirection: 'row',
        backgroundColor: theme.colors.vulcan,
        height: getTabbarHeight(),
      }}
    >
      {state.routes.map((route: any, 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) {
            navigation.navigate(route.name);
          }
        };

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

        return (
          <TabButton
            // eslint-disable-next-line
            key={index}
            isFocused={isFocused}
            options={options}
            route={route}
            onPress={onPress}
            onLongPress={onLongPress}
          />
        );
      })}
    </View>
  );
}
