import React, { PropTypes } from 'react';
import classNames from 'classnames';
import Comment from './Comment';
import './Comments.less';

const sortComments = (comments, sortType = 'BEST') => {
  const sortedComments = [...comments];

  switch (sortType) {
    case 'BEST':
      return sortedComments.sort((a, b) => a.net_votes - b.net_votes).reverse();
    case 'TRENDING':
      return sortedComments.sort((a, b) => {
        const compareRes = parseFloat(a.pending_payout_value) - parseFloat(b.pending_payout_value);
        return compareRes || a.net_votes - b.net_votes;
      }).reverse();
    case 'NEWEST':
      return sortedComments.sort((a, b) => Date.parse(a.created) - Date.parse(b.created)).reverse();
    default:
      return sortedComments;
  }
};

class Comments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sort: 'BEST',
    };
  }

  handleSortClick = (e) => {
    const type = e.target.dataset.type;
    if (type) {
      this.setState({
        sort: type,
      });
    }
  };

  render() {
    const { comments, commentsChildren } = this.props;
    const { sort } = this.state;

    return (
      <div className="Comments">
        <div className="Comments__sort" onClick={this.handleSortClick}>
          <a className={classNames({ active: sort === 'BEST' })} data-type="BEST">Best</a>
          <a className={classNames({ active: sort === 'TRENDING' })} data-type="TRENDING">Trending</a>
          <a className={classNames({ active: sort === 'NEWEST' })} data-type="NEWEST">Newest</a>
        </div>
        {
          comments && sortComments(comments, sort).map(comment =>
            <Comment key={comment.id} comment={comment} commentsChildren={commentsChildren} />
          )
        }
      </div>);
  }
}

Comments.propTypes = {
  comments: PropTypes.arrayOf(PropTypes.shape()),
  commentsChildren: PropTypes.shape(),
};

export default Comments;

@@ -359,24 +359,22 @@
   case '
-TRENDING
+NEWEST
 ':%0A     
@@ -415,173 +415,53 @@
  =%3E 
-%7B%0A        const compareRes = parseFloat(a.pending_payout_value) - parseFloat(b.pending_payout_value);%0A        return compareRes %7C%7C a.net_votes - b.net_votes;%0A      %7D
+Date.parse(a.created) - Date.parse(b.created)
 ).re
@@ -471,35 +471,35 @@
 se();%0A    case '
-NEW
+OLD
 EST':%0A      retu
@@ -573,34 +573,24 @@
 (b.created))
-.reverse()
 ;%0A    defaul
@@ -1277,24 +1277,22 @@
 rt === '
-TRENDING
+NEWEST
 ' %7D)%7D da
@@ -1304,26 +1304,22 @@
 pe=%22
-TRENDING%22%3ETrending
+NEWEST%22%3ENewest
 %3C/a%3E
@@ -1366,35 +1366,35 @@
 tive: sort === '
-NEW
+OLD
 EST' %7D)%7D data-ty
@@ -1393,35 +1393,35 @@
  data-type=%22
-NEW
+OLD
 EST%22%3E
-New
+Old
 est%3C/a%3E%0A    

Remove trending and add oldest sorting