import React from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { Header, Footer } from "../layout"
import Donut from "../charts/Donut";
import './css/salesByRegions.css';
import * as actions from "../../actions/propertysale/sales_by_regions";

class SalesByRegions extends React.Component {
    static propTypes = {
        error: PropTypes.string,
        loading: PropTypes.bool.isRequired,
        data: PropTypes.array,
        fetch_data: PropTypes.func.isRequired,
    };

    componentDidMount() {
        this.props.fetch_data(this.props.year);
    }

    render() {
        return <div>
            <Header/>
            <h2>Répartiton du nombre de ventes par région</h2>
            {
                this.props.error &&
                <h3 style={{ color: "red" }}>{this.props.error}</h3>
            }
                    <select class="custom-select"
                        onChange={ e =>
                            this.props.fetch_data(e.target.value)
                        }
                    >
                        <option>2015</option>
                        <option>2016</option>
                        <option>2017</option>
                        <option>2018</option>
                        <option>2019</option>
                    </select>
            {
                this.props.loading ?
                    <h3>Chargement...</h3>
                    :
                    
                    <Donut data={this.props.data} />
            }
            <Footer/>
        </div>;
    }
}

const mapStateToProps = state => {
    const {
        propertysale: {
            salesbyregion: {//doit respecter la case du combiner des reducers, sinon le data récupéré est vide
                year = 2015,
                data = [],
                loading = false,
                error,
            } = {},
        } = {},
    } = state;

    return { year, data, loading, error };
}

const mapDispatchToProps = dispatch => ({
    fetch_data: (year) => dispatch(actions.fetch_data(year)),
});

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