import React from 'react';
import {State, Navigation} from 'react-router';
import Reflux from 'reflux';
import StoreMixin from 'reflux-immutable/StoreMixin';

// Components
import Color from 'trc-client-core/src/components/Color';
import {STREAM_CERTIFICATION_CSV} from 'trc-client-core/src/constants/Endpoints';
import COLORS from 'trc-client-core/src/constants/Color';
import Loader from 'trc-client-core/src/components/Loader.jsx';
import PrintChartView from './PrintChartView';
import Column from 'bd-peanut/components/Column.jsx';
import TechnicalReportStore from 'trc-client-core/src/report/TechnicalReportStore';
import ReportActions from 'trc-client-core/src/report/ReportActions';
import ColumnDataTable from 'trc-client-core/src/components/ColumnDataTable';

//Modals
import ModalManager from '../Modal/ModalManager';
import InformationModal from '../components/InformationModal';


var StreamCertificationChart = React.createClass({
    displayName: 'StreamCertificationChart',
    contextTypes: {
        location: React.PropTypes.object
    },
    mixins: [
        State,
        Navigation,
        StoreMixin,
        Reflux.listenTo(TechnicalReportStore, 'onStoreChange')
    ],
    getDefaultProps() {
        return {
            certCode: 'ANY'  
        };
    },
    getStoreState() {
        return {
            streamCertification: TechnicalReportStore.get('streamCertification').toJS(),
            fetching: TechnicalReportStore.get('streamCertificationFetching')
        };
    },
    componentDidMount() {
        this.getData(this.props);
    },
    componentWillReceiveProps(nextProps) {
        if(
            this.props.certCode !== nextProps.certCode ||
            this.props.dealerCode !== nextProps.dealerCode ||
            this.props.regionCode !== nextProps.regionCode
        ) {
            this.getData(nextProps);
        }  
    },
    getData(props) {      
        ReportActions.fetchStreamCertification({
            certCode: props.certCode,
            dealer: props.dealerCode
        });        
    },
    getCurrentColorSeries: function () {
        var colorCode = this.props.certCode.split('_')[0];

        if(colorCode === 'ANY') {
            colorCode = 'PT';
        }

        var color = new Color(COLORS.TOYOTA.TECHNICAL[colorCode]);
        return [
            color.hexString(),
            color.lighten(0.5).hexString(),
            '#e6e6e6'
        ];
    },
    onShowLegend: function () {
        ModalManager.showModal(InformationModal, {
            title: 'Stream Certification',
            children: this.renderLegend()
        });
    },
    render: function(){
        if(!this.state.streamCertification.chartMax) {
            return <Loader></Loader>;
        }
        
        var {chartMax} = this.state.streamCertification;
        if(this.props.certCode === 'MT_CERT') {
            chartMax = chartMax * 0.1;
        }

        var legend = ['Certified', 'Eligible', 'Total'];
        var tableHeaders = ['Certified', 'Eligible', 'Total', 'Benchmark', 'Gap'];
        var fetching = this.state.fetching ? 'is-fetching' : '';

        var {location} = this.context;

        return <div>
            <div className={"Chart Chart-stacked " + fetching }>  
                <Column 
                    modifier="tight stacked" 
                    data={this.state.streamCertification.streamCertificationTotal}
                    yAxisMax={chartMax}
                    colors={['#e6e6e6']}
                    yAxisLabel={'Number of Staff'}
                />
                <Column 
                    modifier="tight stacked"
                    type="stacked"
                    data={this.state.streamCertification.streamCertification} 
                    legend={legend} 
                    colors={this.getCurrentColorSeries()}
                    columnStyle={this.renderColumn}
                    yAxisMax={chartMax}
                    displayAxis={false}
                />
                <Column 
                    modifier="tight line"
                    data={this.state.streamCertification.streamCertificationBenchmark} 
                    colors={['#aaa']}
                    yAxisMax={chartMax}
                    displayAxis={false}
                />
                <ColumnDataTable headers={tableHeaders} data={this.state.streamCertification.streamCertificationTable}/>
                <PrintChartView href={(location.pathname+location.search).replace(location.pathname, STREAM_CERTIFICATION_CSV)}/>                
            </div>
        </div>;
    },
    renderColumn: function (dd, ee) {
        var {certCode} = this.props;
        if(certCode === 'ANY') {
            certCode = ee.xlabel;
        }

        var color = Color('#eb2136');
        var darkenValue = (dd === ee.series[0]) ? 0 : 0.5;
        // Set Color
        if (certCode.indexOf('ST_') !== -1) {
            color = Color('#00adee');
        } else if (certCode.indexOf('DT_') !== -1) {
            color = Color('#3dae48');
        } else if (certCode.indexOf('MT_') !== -1) {
            color = Color('#c09057');
        }

        return {
            backgroundColor: color.lighten(darkenValue).hexString()
        };  
    },
    renderLegend: function () {
        return (
            <div className="Typography">
                <p>The Stream Certification Report is generated using the following details.</p>                 
                <p>All the certification course codes to be found in:</p>
                <ul>
                    <li>Pro Tech</li>
                    <li>Service Tech</li>
                    <li>Diagnosis Tech</li>
                    <li>Master Tech</li>
                </ul>
                <p>Staff to be included in the report will be:</p>
                <ul>
                    <li><code>6425 - Apprentice</code></li>
                    <li><code>6601 - Technician</code></li>
                    <li><code>6347 - Workshop Foreman</code></li>
                    <li><code>6421 - Diagnosis Master Technician</code></li>
                    <li><code>6320 - Road Tester</code></li>
                </ul>
                <p>Eligibility determined via logic:</p>
                <ul>
                    <li>If a user does not have ST, they are eligible for ST.</li>
                    <li>If a user has ST but not PT, they are eligible for PT.</li>
                    <li>If a user has PT but not all four DT certs, they are eligible for them. It will calculate no. of eligibles for each cert.</li>
                    <li>If a user has all four DTs, they are eligible for MT.</li>
                </ul>
                <p>Benchmarks:</p>
                <ul>
                    <li>100% of Staff to be ST Certified</li>
                    <li>50% of Staff to be PT Certified</li>
                    <li>30% of Staff to be DT Certified in at least one Stream</li>
                    <li>10% of Staff to be MT Certified</li>
                </ul>
                <p><em>NB: To best display the 10% Benchmark of Certifications the MT chart has been 'zoomed in'; the full data is displayed in the table below the chart.</em></p>
            </div>
        );
    }
});

module.exports = StreamCertificationChart;