import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Button, Row, Col} from 'reactstrap';
import Select from 'react-select';
import AddOrderProject from './AddOrderProject.jsx';
import {getOrderProjects} from '../../../actions/orderProjects/orderProjectsActions';
import {setDialogOpenFlag, setDialogContent} from '../../../actions/dialog/dialogActions';
import '../style/OrderProjects.css';

class OrderProjectsSelect extends Component {
    constructor(props) {
        super(props);

        this.openDialog = this.openDialog.bind(this);
    }

    componentDidMount(){
      this.props.dispatch(getOrderProjects());
    }

    openDialog(){
        const dialogContent = {
            header: 'Add Project',
            TagName: AddOrderProject,
            class: 'user-dialog',
            hasCloseIcon: true
        };

        this.props.dispatch(setDialogOpenFlag(true));
        this.props.dispatch(setDialogContent(dialogContent));
    }

    render() {
        const {orderProjects, isLoading, idProject, handleChange} = this.props;

        return (<Col md={4} id="order-projects">
            {
              isLoading &&
              <div className="loader">
                  <i className="fa fa-spinner fa-spin fa-3x" aria-hidden="true"></i>
              </div>
            }
            {orderProjects && !isLoading &&
              <Row>
                  <Col md={10}>
                      <Select value={idProject}
                          name="idProject"
                          className="order-project-select"
                          placeholder="Project..."
                          options={orderProjects}
                          clearable={true}
                          onChange={(project) => {handleChange(project)}}/>

                  </Col>
                  <Col md={2}>
                      <Button onClick={this.openDialog} className="actions-button">
                          <i className="fa fa-plus" aria-hidden="true"></i>
                      </Button>
                  </Col>
              </Row>
            }
        </Col>);
    }
}

const mapStateToProps = (state) => ({
    orderProjects: state.orderProjectsReducer.orderProjects,
    isLoading: state.orderProjectsReducer.isLoading
});

export default connect(mapStateToProps)(OrderProjectsSelect);
