import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import FlatButton from 'material-ui/FlatButton';
import CloseIcon from 'material-ui/svg-icons/navigation/close';
import bindAppHistory from './../../utils/bindAppHistory';

import injectF from './../../utils/injectF';
import injectPush from './../../utils/injectPush';
import TopBar from './../../components/TopBar/TopBar';
import SearchBar from './../../components/SearchBar/SearchBar';
import {search} from './../../redux/modules/crossFolderSearch';
import {setCachePageCrossFolderSearch} from './../../redux/modules/cache';
import Pagination from './../../components/Pagination/Pagination';

const styles = require('./PageCrossFolderSearch.scss');

@connect(({crossFolderSearch, cache}) => ({
  isSearching: crossFolderSearch.get('isSearching'),
  cache: cache.get('cachePageCrossFolderSearch'),
  total: crossFolderSearch.get('total'),
  perpage: crossFolderSearch.get('perpage'),
  folders: crossFolderSearch.get('folders')
}), {search, setCachePageCrossFolderSearch})
@injectPush
@injectF
@bindAppHistory
export default class PageCrossFolderSearch extends Component {

  static propTypes = {
    total: PropTypes.number.isRequired,
    push: PropTypes.func.isRequired,
    perpage: PropTypes.number.isRequired,
    cache: PropTypes.object.isRequired,
    search: PropTypes.func.isRequired,
    isSearching: PropTypes.bool.isRequired,
    setCachePageCrossFolderSearch: PropTypes.func.isRequired,
    folders: PropTypes.array.isRequired,
    f: PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);
    this.state = Object.assign({
      searchKeyword: '',
      page: 1
    }, props.cache);
  }

  componentWillMount() {

    const {page, searchKeyword} = this.state;
    const {perpage, search} = this.props;

    search({
      page,
      perpage,
      searchKeyword: searchKeyword.trim()
    });
  }

  componentWillUpdate(nextProps, nextState) {
    const {page, searchKeyword} = this.state;
    const {perpage, search, setCachePageCrossFolderSearch} = this.props;

    const nextPage = nextState.page;
    const nextPerpage = nextProps.perpage;
    const nextSearchKeyword = nextState.searchKeyword;

    const shouldSearch = (page !== nextPage) || (perpage !== nextPerpage) ||
      (searchKeyword !== nextSearchKeyword);

    if (shouldSearch) {

      setCachePageCrossFolderSearch({
        page: nextPage,
        searchKeyword: nextSearchKeyword
      });

      search({
        page: nextPage,
        perpage: nextPerpage,
        searchKeyword: nextSearchKeyword.trim()
      });
    }
  }

  goToFoldersPage = () => this.props.push('/');

  handleClearSearchButtonTouchTap = () => {
    this.setState({searchKeyword: ''});
    this.refs.searchBar.getWrappedInstance().getWrappedInstance().clear();
  };

  handleSearchInputChange = (searchKeyword) => {
    if (this.state.searchKeyword !== searchKeyword) {
      this.setState({page: 1});
    }
    this.setState({searchKeyword});
  };

  handleFolderAnchorTouchTap = (folderId) => {
    return () => this.props.push(`/folders/${folderId}/entries`);
  };

  handleEntryAnchorTouchTap = (entry) => {
    return () => this.props.push(`/folders/${entry.folderId}/entries/${entry.id}`);
  };

  renderEntries(entries) {
    const rows = entries.map((entry) => {
      return (
        <li key={`entry-row-${entry.id}`}>
          <a onTouchTap={this.handleEntryAnchorTouchTap(entry)}>{entry.sourceEntry}</a>
        </li>
      );
    });
    return <ul className={styles.entryBox}>{rows}</ul>;
  }

  renderFolders() {
    const rows = this.props.folders.map(({id, name, entries}) => {
      return (
        <div key={`folder-row-${id}`} className={styles.folder}>
          <a onTouchTap={this.handleFolderAnchorTouchTap(id)}>{name}</a>
          {this.renderEntries(entries)}
        </div>
      );
    });
    return <div className={styles.folderBox}>{rows}</div>;
  }

  handlePageButtonTouchTap = (page) => {
    this.setState({page});
  };

  render() {
    const {searchKeyword, page} = this.state;
    const {f, total, perpage, isSearching} = this.props;

    return (
      <div className={styles.pageCrossFolderSearch}>
        <TopBar>
          <h2>{f('cross-folder-search')}</h2>
          <FlatButton icon={<CloseIcon />} onTouchTap={this.goToFoldersPage} />
        </TopBar>
        <SearchBar ref="searchBar" onInputChange={this.handleSearchInputChange} isLoading={isSearching}
          searchKeyword={searchKeyword} matchedCount={total} autoFocus
          onClearFilterButtonTouchTap={this.handleClearSearchButtonTouchTap} />
        {this.renderFolders()}
        {(total > perpage) && <Pagination current={page} total={Math.ceil(total / perpage)}
          onButtonTouchTap={this.handlePageButtonTouchTap} />}
      </div>
    );
  }
}

@@ -253,16 +253,76 @@
 story';%0A
+import CircularProgress from 'material-ui/CircularProgress';
 %0Aimport 
@@ -3646,24 +3646,342 @@
 Folders() %7B%0A
+    const %7Bpage%7D = this.state;%0A    const %7Btotal, perpage, isSearching%7D = this.props;%0A%0A    if (isSearching) %7B%0A      return (%0A        %3CCircularProgress mode=%22indeterminate%22 size=%7B80%7D%0A          style=%7B%7BtextAlign: 'center', marginTop: '80px', marginRight: 'auto', marginLeft: 'auto', display: 'block'%7D%7D /%3E%0A      );%0A    %7D%0A%0A
     const ro
@@ -4252,32 +4252,33 @@
      );%0A    %7D);%0A
+%0A
     return %3Cdiv 
@@ -4272,16 +4272,38 @@
  return 
+(%0A      %3Cdiv%3E%0A        
 %3Cdiv cla
@@ -4340,16 +4340,190 @@
 s%7D%3C/div%3E
+%0A        %7B(total %3E perpage) && %3CPagination current=%7Bpage%7D total=%7BMath.ceil(total / perpage)%7D%0A          onButtonTouchTap=%7Bthis.handlePageButtonTouchTap%7D /%3E%7D%0A      %3C/div%3E%0A    )
 ;%0A  %7D%0A%0A 
@@ -4636,14 +4636,8 @@
 word
-, page
 %7D = 
@@ -4664,33 +4664,24 @@
 t %7Bf, total,
- perpage,
  isSearching
@@ -5214,163 +5214,8 @@
 ()%7D%0A
-        %7B(total %3E perpage) && %3CPagination current=%7Bpage%7D total=%7BMath.ceil(total / perpage)%7D%0A          onButtonTouchTap=%7Bthis.handlePageButtonTouchTap%7D /%3E%7D%0A
     

add loading indicator in container PageCrossFolderSearch