import React from 'react';
import Grid from "react-css-grid";
import Loading from "../components/Loading";
import VideoItem from "../components/VideoItem";
import PropTypes from "prop-types";
import {getSearchResults} from "../actions/search";
import connect from "react-redux/es/connect/connect";

class Results extends React.Component {

  componentDidMount() {
    // get params from url
    const categoryKey = this.props.match.params.categoryKey;
    const searchValue = this.props.match.params.searchValue;

    //FIXME: first check if current key / value / results is already in state
    this.props.getSearchResults(categoryKey, searchValue);
  }

  render() {
    // console.log('results', this.props.searchResults);
    return (
      <div>
        <Grid className="random-topics"
              width={220}
              gap={12}>
          {this.props.loadingResults && (
            <Loading />
          )}
          {this.props.searchResults && this.props.searchResults.map(video =>
            <VideoItem id={video.id} key={video.id} title={video.title}/>
          )}
        </Grid>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  searchResults: state.results.currentItems,
  currentKey: state.results.currentKey,
  currentValue: state.results.currentValue,
  currentQuery: state.results.queryParams,
  loadingResults: state.results.loadingResults
});

const mapDispatchToProps = dispatch => ({
  // the category key is either {topic, date, date}
  // the search value could be something like 25th-jan.
  getSearchResults: (categoryKey, searchValue) => dispatch(getSearchResults(categoryKey, searchValue)),
});

// each result page has :
// - currentKey:  858.ma/{key}/ where key could be like 'topic'
// - currentValue: 858.ma/topic/{value} where value could be like 'alaa abd al fatah'
// - currentQuery: 858.ma/{query} ?? not getting this! @TODO: clarify this please.
// - currentItems: the list of items/videos.
Results.propTypes = {
  // the category key is either a {topic, location, date}.
  currentKey: PropTypes.string,
  currentValue: PropTypes.string,
  currentItems: PropTypes.array,
  loading: PropTypes.bool,
  categoryItemCount: PropTypes.number,
  getSearchResults: PropTypes.func
};

export default connect(mapStateToProps, mapDispatchToProps)(Results);