import React from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet } from 'react-native'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { withLinkRouter } from '../utils/withLinkRouter'
import { htmlAttrs } from '../utils/htmlAttrs'
import { PressableItem } from './PressableItem'
import { useThemeTokensCallback } from '../ThemeProvider/useThemeTokens'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs])

const styles = StyleSheet.create({
  itemContainer: {
    display: 'flex',
    margin: 0
  },
  childContainer: {
    paddingLeft: 16
  },
  nestedChildContainer: {
    paddingLeft: 24
  }
})

const ListboxItemInner = React.forwardRef(
  (
    {
      href,
      label,
      isChild = false,
      nestedChild,
      onBlur,
      nextItemRef,
      prevItemRef,
      tokens,
      variant = {},
      LinkRouter,
      linkRouterProps,
      id,
      onPress = () => {},
      ...rest
    },
    ref
  ) => {
    const selectedProps = selectProps({ href, ...rest })

    const getTokens = useThemeTokensCallback('Listbox', tokens, variant, { isChild })
    return (
      <View
        style={[
          styles.itemContainer,
          isChild && styles.childContainer,
          nestedChild && styles.nestedChildContainer
        ]}
        role="option"
      >
        <PressableItem
          href={href}
          isChild={isChild}
          onPress={onPress}
          onBlur={onBlur}
          nextItemRef={nextItemRef}
          prevItemRef={prevItemRef}
          ref={ref}
          tokens={getTokens}
          selectedProps={selectedProps}
          id={id}
        >
          {label}
        </PressableItem>
      </View>
    )
  }
)
ListboxItemInner.displayName = 'ListboxItem'

ListboxItemInner.propTypes = {
  ...selectedSystemPropTypes,
  ...withLinkRouter.propTypes,
  href: PropTypes.string,
  isChild: PropTypes.bool,
  label: PropTypes.node.isRequired,
  nextItemRef: PropTypes.object,
  prevItemRef: PropTypes.object,
  onPress: PropTypes.func,
  nestedChild: PropTypes.bool
}

export const ListboxItem = withLinkRouter(ListboxItemInner)
