import React from "react";
import { View, TouchableOpacity } from "react-native";
import * as Haptics from "expo-haptics";

import { gutters, Palette, Style } from "../styles";
import useLayoutType from "../hooks/useLayoutType";

const TabBar = ({ state = {}, descriptors = {}, navigation = {} }) => {
  const { isDesktop, windowWidth, mediumDesktopBreakpoint, isWeb } =
    useLayoutType();

  return (
    <View
      style={{
        position: "absolute",
        bottom: gutters * 2,
        borderRadius: 500,
        flexDirection: "row",
        height: 60,
        width: "60%",
        alignSelf: "center",
        maxWidth: isDesktop ? 200 : 220,
        borderColor: Palette.ultraLightWhite,
        borderWidth: 3,
        paddingHorizontal: 1.2 * gutters,
        backgroundColor: Palette.darkPurple,
        ...Style.containerSpaceBetween,
        ...Style.defaultShadows,
      }}
    >
      {state?.routes?.map((route, index) => {
        const { options } = descriptors[route.key];
        const isFocused = state?.index === index;

        const _onPressTabBar = () => {
          if (!isWeb) {
            Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
          }

          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,
          });
        };

        return (
          !options?.hide && (
            <TouchableOpacity
              key={route.key}
              style={{
                alignSelf: "center",
                width: `${100 / state?.routes?.length}%`,
                height: 40,
                ...Style.containerCenter,
              }}
              accessibilityRole="button"
              accessibilityState={isFocused ? { selected: true } : {}}
              accessibilityLabel={options.tabBarAccessibilityLabel}
              testID={options.tabBarTestID}
              onPress={_onPressTabBar}
              onLongPress={onLongPress}
            >
              {options?.tabBarIcon({ focused: isFocused })}
            </TouchableOpacity>
          )
        );
      })}
    </View>
  );
};

export default TabBar;
