import React, { Component, PropTypes } from 'react';
import { CircularProgress, Card, CardHeader, CardText } from 'material-ui';
import NavItem from './NavItem';

const toArray = arg => Array.isArray(arg) ? arg : [arg];
export default class NavList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: props.expanded,
    };
  }

  componentDidMount() {
    this.setState({ expanded: this.props.expanded });
  }

  handleExpandChange = (expanded) => {
    const eventPayload = {
      category: 'NavList Interaction',
      action: `Toggled ${this.props.navName}`,
      label: expanded ? 'open' : 'closed',
    };
    this.props.ReactGA.event(eventPayload);
    this.setState({ expanded });
  };

  render() {
    const fetchingIcon = (
      <CircularProgress mode="indeterminate" color="black" size={20} thickness={2} />
    );

    let listTitle;
    let navItems;
    const { isFetching, currentHash, navName, ncd: listData } = this.props;

    if (!isFetching && listData.contents) {
      listTitle = listData.label;
      if (listData.contents.length === 0) {
        return null;
      }
      // HERE ARE THE NAVITEMS
      navItems = toArray(listData.contents).map((item, counter) => (
        <NavItem
          className="ih-nav-collection-li"
          key={`muiListItem-${counter}`}
          data={item}
          currentHash={currentHash || ''}
          ReactGA={this.props.ReactGA}
        />
      ));
      // If it isn't fetching, and the contents are empty e.g. the user doesn't have security to see
      // them, then return null;
    } else if (!isFetching && !listData.contents) {
      return null;
    }

    const divStyle = { marginBottom: '0px' };
    return (
      <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
        {(!isFetching && <CardHeader title={listTitle} actAsExpander showExpandableButton />) ||
          <CardHeader
            title={navName}
            openIcon={fetchingIcon}
            closeIcon={fetchingIcon}
            actAsExpander
            showExpandableButton
          />}
        {!isFetching &&
          <CardText expandable>
            {navItems}
          </CardText>}
      </Card>
    );
  }
}

NavList.propTypes = {
  ncd: PropTypes.object,
  isFetching: PropTypes.bool,
  navName: PropTypes.string,
  expanded: PropTypes.bool,
  currentHash: PropTypes.string,
  ReactGA: PropTypes.object,
};

NavList.defaultProps = {
  expanded: true,
  ReactGA: { event: () => {} },
};
