import React from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet } from 'react-native'
import { TabBarItem } from './TabBarItem'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'
import { variantProp } from '../utils/props/variantProp'
import { getTokensPropType } from '../utils/props/tokens'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { a11yProps } from '../utils/props/a11yProps'
import { viewProps } from '../utils/props/viewProps'

const selectTabBarContainerStyles = ({
  paddingTop,
  paddingBottom,
  borderTopWidth,
  borderTopColor,
  backgroundColor
}) => ({
  paddingTop,
  paddingBottom,
  borderTopWidth,
  borderTopColor,
  backgroundColor
})

const selectTabBarItemContainerStyles = ({ paddingLeft, paddingRight, gap }) => ({
  paddingLeft,
  paddingRight,
  gap
})

const [selectProps, selectedSystemPropTypes] = selectSystemProps([a11yProps, viewProps])

/**
 * TabBar component renders a navigation bar with multiple TabBarItems.
 * It allows users to switch between different views or sections.
 *
 * @component
 * @example
 * const items = [
 *   { id: '1', label: 'Home', icon: <HomeIcon />, iconActive: <HomeActiveIcon /> },
 *   { id: '2', label: 'Profile', icon: <ProfileIcon />, iconActive: <ProfileActiveIcon /> },
 * ]
 * return (
 *   <TabBar
 *     items={items}
 *     initiallySelectedItem="1"
 *     onChange={(itemId) => console.log(itemId)}
 *     accessibilityLabel="Main navigation"
 *   />
 * )
 */

export const TabBar = React.forwardRef(
  (
    {
      items = [],
      initiallySelectedItem = '0',
      onChange,
      variant,
      tokens,
      accessibilityLabel,
      ...rest
    },
    ref
  ) => {
    const [isSelected, setIsSelected] = React.useState(initiallySelectedItem)
    const themeTokens = useThemeTokens('TabBar', tokens, variant)

    const handlePress = (itemId) => {
      setIsSelected(itemId)
      onChange?.(itemId)
    }

    return (
      <View
        ref={ref}
        style={[styles.tabBar, selectTabBarContainerStyles(themeTokens)]}
        {...selectProps(rest)}
      >
        <View
          style={[styles.tabBarItem, selectTabBarItemContainerStyles(themeTokens)]}
          accessibilityRole="tablist"
          accessibilityLabel={accessibilityLabel}
        >
          {items.map((item, index) => (
            <TabBarItem
              key={item.id}
              label={item.label}
              href={item.href}
              isSelected={isSelected === item.id}
              icon={item.icon}
              iconActive={item.iconActive}
              onPress={() => handlePress(item.id)}
              id={`tab-item-${index}`}
              tokens={item.tokens}
            />
          ))}
        </View>
      </View>
    )
  }
)

TabBar.displayName = 'TabBar'

TabBar.propTypes = {
  ...selectedSystemPropTypes,
  /** Array of TabBarItems to be displayed in TabBar */
  items: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      icon: PropTypes.node,
      iconActive: PropTypes.node,
      label: PropTypes.string.isRequired,
      href: PropTypes.string,
      tokens: getTokensPropType('TabBarItem')
    })
  ).isRequired,
  /** Id of the initially selected item. */
  initiallySelectedItem: PropTypes.number,
  /** Callback function to handle item selection change. */
  onChange: PropTypes.func,
  /** Variant of TabBar for styling purposes. */
  variant: variantProp.propType,
  /** Tokens for theming and styling. */
  tokens: getTokensPropType('TabBar'),
  /** Accessible label for the tab bar navigation region, used by screen readers to identify the tablist. */
  accessibilityLabel: PropTypes.string
}

const styles = StyleSheet.create({
  tabBar: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  tabBarItem: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%'
  }
})
