import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import KdLoading from '../KdLoading';
import Popover from 'react-bootstrap/lib/Popover';

const propTypes = {
  onRemove: PropTypes.func,
  kdFilterModel: PropTypes.object.isRequired,
  api: PropTypes.shape({
    url: PropTypes.string.isRequired,
    key: PropTypes.string.isRequired,
  }),
  label: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
}

class KdPopover extends React.Component {
  constructor(props) {
    super(props);

    this.fetchItemInfo = this.fetchItemInfo.bind(this);
    this.handleOutsideClick = this.handleOutsideClick.bind(this);
    this.renderItemInfo = this.renderItemInfo.bind(this);

    this.state = { isLoading: false, popoverInfo: [] };
  }

  componentWillMount(){
    document.addEventListener('click', this.handleOutsideClick, false);
    this.setState({ isLoading: true });
    this.fetchItemInfo(this.props.label);
  }

  handleOutsideClick(e) {
    if (!ReactDOM.findDOMNode(this).contains(e.target)) {
      this.props.onRemove && this.props.onRemove();
    }
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleOutsideClick, false);
  }

  fetchItemInfo(value){
    const { kdFilterModel, api } = this.props;
    if (value.length) {
      const onRequestDone = (data) => {
        this.setState({
          isLoading: false,
          popoverInfo: data.KdResult.Result[0]
        });
      };
      let request = kd.Request(kdFilterModel.getEntityType(), 'Search');
      request.setUrlBase(api.url);
      request.setApiKey(api.key);
      request.setAjaxDone(onRequestDone);
      request.setQ(value);
      request.requestData();
    }
  }

  renderItemInfo(){
    const { popoverInfo } = this.state;
    let itemInfo = [];
    for ( const key in popoverInfo ) {
      if (popoverInfo.hasOwnProperty(key)) {
        itemInfo.push(
          <div key={key} className="c-kd-popover__details" >
            <span className="c-kd-popover__label"> {key} </span>
            <span className="c-kd-popover__value"> {`${popoverInfo[key]}`} </span>
          </div>
        )
      }
    }
    return (
      <div className="c-kd-popover__body">
        {itemInfo}
      </div>
    );
  }

  render() {
    return (
      <div className="c-kd-popover">
        <Popover
          id="kd-popover"
          placement="top"
          className="c-kd-popover"
          positionTop={-254}
          title={this.props.label} >

          {this.state.isLoading ? <KdLoading /> : this.renderItemInfo()}
        </Popover>
      </div>
    );
  }

}

export default KdPopover;