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

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

// Stampy
import ColumnDataTable from 'trc-client-core/src/components/ColumnDataTable';

import Icon from 'trc-client-core/src/components/Icon';
import Column from 'bd-peanut/components/Column';
import COLORS from 'trc-client-core/src/constants/Color';
import PrintChartView from 'trc-client-core/src/report/PrintChartView';
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 Label from 'bd-stampy/components/Label';

// Components
import Loader from 'trc-client-core/src/components/Loader';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';
import TechnicalReportStore from 'trc-client-core/src/report/TechnicalReportStore';
import ReportActions from 'trc-client-core/src/report/ReportActions';
import InformationModal from 'trc-client-core/src/components/InformationModal';
import Select from 'trc-client-core/src/components/Select';

import RegionSelect from 'trc-client-core/src/components/RegionSelect';
import YearSelect from 'trc-client-core/src/components/YearSelect';
import TechnicalTrainerSelect from 'trc-client-core/src/components/TechnicalTrainerSelect';
import Page from 'trc-client-core/src/components/Page';

var defaultQuery = {
    graph: 'days',
    regionCode: 'ALL_REGIONS',
    trainerName: 'ANY_TRAINER',
    year: moment().year().toString(),
    year_type: 'jp_fiscal'                
};

var TrainingDeliveryHoursReport = React.createClass({
    displayName: 'TrainingDeliveryHoursReport',
    mixins: [
        State,
        History,
        StoreMixin,
        Reflux.listenTo(TechnicalReportStore, 'onStoreChange')
    ],
    getStoreState() {
        return {
            trainingDelivery: TechnicalReportStore.get('trainingDelivery').toJS(),
            fetching: TechnicalReportStore.get('trainingDeliveryFetching')
        };
    },
    componentWillMount() {
        this.history.replaceState(null, '/report/training_delivery', _.defaults(this.props.location.query, defaultQuery));
    },
    componentDidMount() {
        this.getData();
    },
    getData() {
        ReportActions.fetchTrainingDelivery(this.props.location.query);        
    },
    onShowLegend() {
        ModalManager.showModal(InformationModal, {
            title: 'Technical Training Delivery',
            children: (
                <div className="Typography">           
                    <p>The Technical Trainer&apos;s Delivery Report is generated using the following details.</p>
                    <p>Tech Trainers will be based on all staff listed as <code>Instructor</code> in <code>Blueflag_SOData</code>, aligned to SOs with the following <code>SO Item Stream</code>:</p>
                    <ul>
                        <li>Protech</li>
                        <li>Servicetech</li>
                        <li>Diagnostictech</li>
                        <li>Mastertech</li>
                    </ul>
                    <p>Additionally, benchmarking is supplied per instructor; if a region has multiple instructors, then their benchmark is combined.</p>
                    <ul>
                        <li>A benchmark of 100 days per annum is supplied by TSO.</li>
                        <li>Benchmark Days (100 days x 8 Techs = 800)</li>
                        <li>Benchmark Hours (100 Day x 8 Techs x 7 Hours = 5600)</li>
                    </ul>
                </div>
            )
        });
    },
    render() {
        return (
            <Page title="Training Delivery Report">
                <div>
                    <h1>Technical Training Delivery <Icon name="circleinfo" onClick={this.onShowLegend}></Icon></h1>            
                    {this.renderQuery()}
                    {this.renderCharts()}
                </div>
            </Page>
        );
    },
    renderQuery() {
        var {year, year_type, regionCode, trainerName, graph} = this.props.location.query;
        return (
            <div className="hide-print">
                <Grid modifier="tight">
                    <Col>
                        <Label>Graph Type</Label>
                        <Select 
                            name="graph" 
                            queryString 
                            value={graph}
                            options={[
                            {label: 'Days', value: 'days'},
                            {label: 'Training Days', value: 'trainingDays'},
                            {label: 'Training Hours', value: 'trainingHours'}
                        ]}/>
                    </Col>
                    <Col>
                        <Label>Year</Label>
                        <YearSelect name="year" value={year} onChange={this.getData} to={2013} />
                    </Col>
                    <Col>
                        <Label>Year Type</Label>
                        <Select 
                            name="year_type" 
                            queryString 
                            value={year_type}
                            onChange={this.getData}
                            options={[
                            {label: 'Japanese Fiscal', value: 'jp_fiscal'},
                            {label: 'Calendar', value: 'calendar'}
                        ]}/>
                    </Col>
                    <Col>
                        <Label>Region</Label>
                        <RegionSelect value={regionCode} onChange={this.getData} />
                    </Col>
                    <Col>
                        <Label>Trainer</Label>
                        <TechnicalTrainerSelect {...this.props.location.query} value={trainerName} onChange={this.getData} />
                    </Col>
                </Grid>
            </div>
        );
    },
    renderCharts(){
        var {location} = this.props;
        if(!this.state.trainingDelivery.days) {
            return <Loader></Loader>;
        }
        
        return (
            <div>
                <h2>Month to Date</h2>
                {this.renderChartMarkup(this.props.location.query.graph, 'actual')}

                <h2>Accumulative</h2>
                {this.renderChartMarkup(this.props.location.query.graph, 'accumulate')}
                <PrintChartView href={(location.pathname + location.search).replace(location.pathname, TECHNICAL_TRAINING_CSV)}/>          
            </div>
        );
    },
    renderChartMarkup(value, type) {
        var fetchingClass = this.state.fetching ? 'is-fetching' : '';
        var legend = ['Actual', 'Enrolled', 'Planned', 'Benchmark'];
        var tableLegend = ['Planned', 'Enrolled', 'Actual', 'Benchmark'];
        var name = value.toLowerCase();
        var colors = [
            COLORS.TOYOTA.HERO, 
            Color(COLORS.TOYOTA.HERO).lighten(0.5).clearer(0.5).hexString(),
            Color(COLORS.TOYOTA.HERO).lighten(0.6).desaturate(0.75).hexString()
        ];

        if(value === 'days') {
            legend = ['Planned', 'Benchmark']; 
            tableLegend = ['Planned', 'Benchmark'];
            colors = [
                Color(COLORS.TOYOTA.HERO).lighten(0.6).desaturate(0.75).hexString()
            ];       
        }

        return (           
            <div className={"Chart Chart-stacked print-pagebreakbefore " + fetchingClass}>
                <Column 
                    modifier="large"
                    data={this.state.trainingDelivery[value][type].graph} 
                    legend={legend} 
                    valueSuffix="hrs" 
                    yAxisMax={this.state.trainingDelivery[value][type].chartMax}
                    colors={colors}
                    yAxisLabel={name}
                />
                <Column 
                    modifier="line"
                    data={this.state.trainingDelivery[value][type].benchmark} 
                    yAxisMax={this.state.trainingDelivery[value][type].chartMax}
                    displayAxis={false}
                />
                <ColumnDataTable headers={tableLegend} data={this.state.trainingDelivery[value][type].table}/>
            </div>   
        );
    },
    renderHoursDays() {
        return (this.state.sortBy && this.state.sortBy.length) ? 'Days' : 'Hours';
    }
});

module.exports = TrainingDeliveryHoursReport;