import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import sortBy from 'lodash/sortBy'
import { fetchEntities } from '../actions/index'
import Admin from '../admin'

interface Page {
  id: number
  name: string
  url: string
}

interface PartialInstancesProps {
  fetchEntities: any;
  pages: any;
}

interface PartialInstancesState extends ComponentState {
  pages: Page[]
}

class PartialInstances extends React.Component<PartialInstancesProps, PartialInstancesState> {

  constructor(props) {
    super(props);
    this.state = {
      fetching: true,
      pages: []
    };
  }

  componentDidMount() {
    let partialId = window.location.pathname.split("/")[3];
    this.props.fetchEntities({
      url: `/admin/api/partials/pages?id=${partialId}`
    }).then(() => {
      this.setState({
        fetching: false,
        pages: this.props.pages
      });
    });
  }

  render() {
    return (
      <div id="partial-instances" className="component">
        <h1>Partial Instances</h1>
        <div className="white-box">
          { Admin.renderSpinner(this.state.fetching) }
          { Admin.renderGrayedOut(this.state.fetching) }
          { this.renderPageInstances() }
        </div>
      </div>
    );
  }

  renderPageInstances() {
    const listItems = sortBy(this.state.pages, 'name').map(page => {
      return(
        <li key={ page.id }>
          <div className="item-page-instance clearfix">
            <p className="name">{ page.name }</p>
            <a className="edit-link light-orange-button" href={ `/admin/pages/${page.id}` }>Edit Page</a>
            <a className="view-link light-orange-button" href={ page.url }>View Page</a>
          </div>
        </li>
      );
    });
    return <ul className="list-page-instances">{ listItems }</ul>;
  }

  componentDidUpdate() {
    $('.match-height-layout').matchHeight();
  }
}

const mapStateToProps = (reducers, props) => {
  return reducers.standardReducer;
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchEntities }, dispatch);
}

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