import React from 'react'
import Modal from 'react-modal'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import PagePartialsNew from './page-partials-new'
import PagePartial from './page-partial'
import Admin from './../admin'
import { PartialsModalStyles } from './helpers/modal-styles'

interface NestedPagePartialProps {
  addNestedPagePartial: any;
  deleteNestedPagePartial: any;
  id: number;
  nestedPagePartials: any[];
  pagePartial: any;
  partials: any[];
  partialFieldId: number;
};

interface NestedPagePartialState {
  isExpanded: boolean;
  partialsModalOpen: boolean;
}

class NestedPagePartial extends React.Component<NestedPagePartialProps, NestedPagePartialState> {

  constructor(props) {
    super(props);

    this.state = {
      isExpanded: false,
      partialsModalOpen: false
    }
  }

  clickAdd() {
    this.setState({
      partialsModalOpen: true
    });
  }

  selectPartial(partialId) {
    this.props.addNestedPagePartial({
      partialId,
      partialFieldId: this.props.partialFieldId
    });
  }

  render() {
    const pagePartial = this.props.pagePartial;
    if (pagePartial) {
      return(
        <PagePartial
          nested={ true }
          parentPartialFieldId={ this.props.partialFieldId }
          passedPagePartial={ pagePartial }
          deleteNestedPagePartial={ this.props.deleteNestedPagePartial.bind(this) }
        />
      );
    } else {
      return(
        <div data-partial-field-id={ this.props.partialFieldId }>
          <a key="1" className="btn green-outline-button" onClick={ this.clickAdd.bind(this) }>
            Add Nested Partial
          </a>,
          <Modal key="2" isOpen={ this.state.partialsModalOpen } onRequestClose={ Admin.closeModals.bind(this) } contentLabel="Modal" style={ PartialsModalStyles }>
            <PagePartialsNew addPartial={ this.selectPartial.bind(this) } closeModal={ Admin.closeModals.bind(this) } partials={ this.props.partials } />
          </Modal>
        </div>
      );
    }
  }
}

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

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

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