/** @jsx createElement */

import { createElement, Component } from 'rax';
import View from 'nuke-view';
import Text from 'nuke-text';
import { isWeb } from 'nuke-env';
import Touchable from 'nuke-touchable';
import { connectStyle } from 'nuke-theme-provider';
import Icon from 'nuke-icon';

import stylesProvider from '../styles';

class Item extends Component {
  constructor(props) {
    super(props);
    this.onPress = this.onPress.bind(this);
    this.selectedIcon = this.selectedIcon.bind(this);
  }
  onPress() {
    this.props._control.switch = false;
    this.props.handleTouchTap(this.props.tabKey, !this.props.preventDefaultEvent);
    if (this.props.onPress) {
      this.props.onPress();
    }
    this.props._control.switch = true;
  }

  selectedIcon() {
    if (this.props.selected && this.props.selectedIcon) {
      return this.props.selectedIcon;
    }
    return this.props.icon;
  }

  render() {
    const {
      index,
      num,
      icon,
      title,
      capsule = false,
      render,
      navStyle = {},
      selected,
      navScrollable,
      navTop,
      style,
      iconBar,
      themeStyle,
    } = this.props;
    const navPosition = capsule ? 'capsule' : navTop ? 'top' : 'bottom';
    const navWrapStyle = Object.assign(
      {},
      themeStyle['nav-item'],
      themeStyle[`nav-item-${navPosition}`],
      !navScrollable && !capsule ? { flex: 1 } : {},
      selected ? themeStyle[`nav-item-${navPosition}-selected`] : {},
      selected ? navStyle.active : navStyle.inactive,
      iconBar ? themeStyle['nav-item-has-icon'] : {},
      capsule && index > 0 ? themeStyle['nav-item-capsule-not-first'] : {},
      style
    );
    if (render) {
      delete navWrapStyle.height;
    }
    if (!navWrapStyle.flex && isWeb) {
    }
    let iconURL;

    let iconSize = 'large';

    let iconStyle;
    if (icon) {
      iconStyle = icon.style;
      iconSize = icon.size ? icon.size : iconSize;
      if (selected) {
        iconURL = icon.selected;
      } else {
        iconURL = icon.src;
      }
    }

    const navTextStyle = Object.assign(
      {},
      themeStyle['nav-item-text'],
      themeStyle[`nav-item-${navPosition}-text`],
      selected ? themeStyle[`nav-item-${navPosition}-selected-text`] : {}
    );
    const itemContent = () => {
      if (!render) {
        return (
          <View style={{ alignItems: 'space-between' }}>
            {icon ? <Icon size={iconSize} src={iconURL} style={[themeStyle.navItemIcon, iconStyle || {}]} /> : null}
            <Text style={navTextStyle}>{title}</Text>
          </View>
        );
      }
    };

    return (
      <Touchable style={navWrapStyle} onPress={this.onPress} t="tab-item">
        {render ? render(selected, this.props.tabKey) : null}
        {itemContent()}
      </Touchable>
    );
  }
}
Item.displayName = 'Item';

export default connectStyle(stylesProvider)(Item);
