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

import {STREAM_ELIGIBILITY_CSV} from 'trc-client-core/src/constants/Endpoints';

// Stampy
import UrlStore from 'bd-stampy/utils/UrlStore';
import Color from 'trc-client-core/src/components/Color';
import Grid from 'trc-client-core/src/components/Grid';
import Col from 'trc-client-core/src/components/Col';
import Icon from 'trc-client-core/src/components/Icon';
import Table from 'bd-stampy/components/Table';
import Button from 'bd-stampy/components/Button';
import ColumnDataTable from 'trc-client-core/src/components/ColumnDataTable';
import Column from 'bd-peanut/components/Column.jsx';


// Components
import Loader from '../components/Loader.jsx';
import ErrorMessage from 'trc-client-core/src/components/ErrorMessage';
import StreamSelect from 'trc-client-core/src/report/StreamSelect';
import RegionSelect from 'trc-client-core/src/components/RegionSelect';
import PrintChartView from 'trc-client-core/src/report/PrintChartView';
import TechnicalReportStore from 'trc-client-core/src/report/TechnicalReportStore.js';
import ReportActions from 'trc-client-core/src/report/ReportActions';
import COLORS from 'trc-client-core/src/constants/Color';

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


var StreamEligibilityReport = React.createClass({
    displayName: 'StreamEligibilityReport',
    mixins: [
        State,
        History,
        StoreMixin,
        Reflux.listenTo(TechnicalReportStore, 'onStoreChange')
    ],
    getStoreState() {
        return {
            streamEligibility: TechnicalReportStore.get('streamEligibility').toJS(),
            fetching: TechnicalReportStore.get('streamEligibilityFetching')
        };
    },
    componentWillMount() {
        this.history.replaceState(null, '/report/stream_eligibility', _.defaults(this.props.location.query, {
            certCode: 'ST_STC',
            regionCode: 'ALL_REGIONS'
        }));
    },
    componentDidMount() {
        this.getData();
    },
    getData() {
        ReportActions.fetchStreamEligibility(UrlStore.getQueryParams());        
    },
    onChange: function (e, details) {
        this.FormMixin_onFormChange(e, details);
    },
    onShowLegend: function () {
        ModalManager.showModal(InformationModal, {
            title: 'Stream Eligibility Report',
            children: this.renderLegend()
        });
    },
    render: function () {
        var {certCode, regionCode} = this.props.location.query;
        return <div>
            <h1><span className="Button Button-small vertical-middle l-inline">Beta</span>Stream Eligibility <Icon name="circleinfo" onClick={this.onShowLegend}></Icon></h1>
            <Grid className="hide-print">
                <Col width={3}>
                    <StreamSelect name="certCode" value={certCode} allOption={false}/>
                </Col>
                <Col width={3}>
                    <RegionSelect name="regionCode" value={regionCode} />
                </Col>
                <Col><Button className="right" disabled={this.state.fetching} onClick={this.getData}>Generate</Button></Col>
            </Grid>
            
            {this.renderCharts()}
        </div>;
    },
    renderCharts: function(){
        var legend = ['Completed', 'Eligible']; 
        var {location} = this.props;

        if(this.state.error) {
            return <ErrorMessage code={this.state.error.status}></ErrorMessage>;
        }

        if(this.state.fetching) {
            return <Loader></Loader>;
        }

        if (this.state.streamEligibility) {
            return <div className="Chart">
                <Column 
                    modifier="tight stacked"
                    type="stacked"
                    data={this.state.streamEligibility} 
                    legend={legend} 
                    tickSize={10}
                    colors={this.getCurrentColorSeries()}
                    columnStyle={this.renderColumn}
                    yAxisLabel={'Number of Staff'}
                /> 
                <ColumnDataTable headers={legend} data={this.state.streamEligibility}/>
                <PrintChartView href={(location.pathname+location.search).replace(location.pathname, STREAM_ELIGIBILITY_CSV)}/>
            </div>;            
        }

    },
    getCurrentColorSeries() {
        var colorCode = this.props.location.query.certCode.split('_')[0];

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

        var color = new Color(COLORS.TOYOTA.TECHNICAL[colorCode]);
        return [
            color.hexString(),
            color.lighten(0.5).hexString()
        ];
    },
    renderColumn: function (dd, ee) {
        var {certCode} = this.props.location.query;
        var label = ee.xlabel;
        var color = Color('#eb2136');

        // Use the formData if the label is a coursecode rather than a certcode
        if(label.indexOf('_') === -1) {
            label = certCode;
        }

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

        return {
            backgroundColor: color.lighten(lightenValue).hexString()
        };
    },
    renderLegend: function () {
        return <div className="Typography">
            <p>Staff Job Roles Displayed:</p>
                <ul>
                    <li><code>Apprentice</code></li>
                    <li><code>Technician</code></li>
                    <li><code>Workshop Foreman</code></li>
                    <li><code>Diagnosis Master Technician</code></li>
                    <li><code>Road Tester</code></li>
                </ul>

            <p>To be eligible for Service Tech, Apprentices must have been in the role for 12 months, and Technician, Workshop Foreman, Diagnosis Master Technician, Road Tester must have been in their role for 3 months. <br/><em>Note: Not yet applicable, coming soon.</em></p>

            <Table headings="Stream, Prerequisite, Prerequisite Code">
                <tr><td>Pro Tech</td>           <td>Service Tech Certification</td> <td><code>ST_STC</code></td></tr>
                <tr><td>DT Foundations</td>     <td>Pro Tech Certification</td>     <td><code>PT_PTC</code></td></tr>
                <tr><td>DT Hybrid</td>          <td>DT Foundations</td>             <td><code>T21-DTFD1</code></td></tr>
                <tr><td>DT Engine</td>          <td>DT Foundations</td>             <td><code>T21-DTFD1</code></td></tr>
                <tr><td>DT Chassis</td>         <td>DT Foundations</td>             <td><code>T21-DTFD1</code></td></tr>
                <tr><td>DT Electrical</td>      <td>DT Foundations</td>             <td><code>T21-DTFD1</code></td></tr>
                <tr><td>Master Tech</td>        <td>All DT Certifications</td>      <td><code>DT_HYBC</code><code>DT_ELC</code><br/><code>DT_ENC</code><code>DT_CHC</code></td></tr>
            </Table>
        </div>;
    }
});

module.exports = StreamEligibilityReport;