import classnames from 'classnames';
import CourseActivityModal from 'trc-client-core/src/course/CourseActivityModal';
import CourseButton from 'trc-client-core/src/components/CourseButton';
import Icon from 'trc-client-core/src/components/Icon';
import LearningPlanFooter from 'trc-client-core/src/learningPlan/LearningPlanFooter';
import LearningPlanHeader from 'trc-client-core/src/learningPlan/LearningPlanHeader';
import Loader from 'trc-client-core/src/components/Loader';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';
import React from 'react';
import UserStore from 'trc-client-core/src/user/UserStore';
import {Map} from 'immutable';
import {titleCase} from 'trc-client-core/src/utils/Strings';

var LearningPlan = React.createClass({
    displayName: 'LearningPlan',
    getInitialState() {
        return {
            view: 'segments'
        };
    },
    onCourseClick(course) {
        var participant = this.getPathwayCompletion();
        if(course.type !== 'CERTIFICATION') {
            ModalManager.showModal(CourseActivityModal, {
                courseCode: course.get('courseCode'),
                pathwayId: this.props.learningPlanId,
                actionable: participant.get('participantId') === UserStore.get('participantId') || course.get('type') === 'FACE_TO_FACE',
                participantId: participant.get('participantId')
            });
        }
    },
    getPathwayCompletion() {
        if(this.props.learningPlan) {
            return this.props.learningPlan.getIn(['pathwayCompletion', 0]);
        }

        return Map();
    },
    getCompletionPercentage(){
        return this.props.learningPlan
            .getIn(['pathwayCompletion', 0, 'gapData'])
            .filter(course => course.get('segment') !== 'NON_CRITICAL')
            .map(course => course.get('completed'))
            .reduce((reduction, value, key, list) => (value) ? Math.floor(reduction + 100 / list.size) : reduction, 0);
    },
    render() {
        if(!this.props.learningPlan) {
            return <Loader></Loader>;
        }
        var participant = this.getPathwayCompletion();
        return (
            <div>
                {this.renderHeroText()}

                <h1>
                    <span className="t-capitalize">{this.props.learningPlan.get('displayName')}</span>
                    <div className="t-muted">{`${participant.get('firstName')} ${participant.get('lastName')} `}</div>
                </h1>
                <LearningPlanHeader learningPlan={this.props.learningPlan.get('learningPlan')}/>
                {this.renderPlan()}
                <LearningPlanFooter learningPlan={this.props.learningPlan.get('learningPlan')}/>
            </div>
        );
    },
    renderHeroText() {
        //
        // TODO:
        // Toyota can't properly isolate the users to correct courses.
        // So still not all courses in tfl learning plans are applicable
        // to the user assigned it.
        //
        // And then they just decided it would be better to hide them all.
        // Check git history for switch case if they want to go back to hte half and half
        //

        return null;
        // return <div
        //     className="HeroText margin-left right"
        //     style={{ color: this.getCompletionColor() }}
        //     children={`${this.getCompletionPercentage()}%`}
        // />
    },
    renderPlan() {
        if(!this.props.learningPlan) {
            return <Loader />
        }
        switch(this.state.view) {
            case 'segments':
                return this.renderSegments();
        }
    },
    renderSegments() {
        var segments = this.getPathwayCompletion().get('gapData').groupBy(ii => ii.get('segment'));

        return segments
            .map((segment, key) => {
                var opacityValue = 100 - (segments.size - segments.keySeq().indexOf(key)) * 20;
                var barClasses = classnames({
                    'Bar margin-bottom margin-top': true,
                    [`ui-opacity--${opacityValue}`]: true,
                    'Bar-muted': key === 'NON_CRITICAL',
                    [`Bar-${this.getPathwayCompletion().get('department')}`]: key !== 'NON_CRITICAL'
                });
                return <div key={key}>
                    <div className={barClasses}>{titleCase(key.replace('_', ' '))}</div>
                    <table className="Table">
                        <tbody>
                            <tr className="t-muted">
                                <td className="w75"></td>
                                <td>Complete</td>
                                <td className="w25 t-center">Current Status</td>
                            </tr>
                            {segment.map(this.renderRow)}
                            {this.renderOldCertifications(key)}
                        </tbody>
                    </table>
                </div>;
            }).toList().toJS();
    },
    renderRow(course, key) {
        return (course.get('type') === 'CERTIFICATION')
            ? this.renderCertificationRow(course, key)
            : this.renderCourseRow(course, key);
    },
    renderOldCertifications(segment) {
        var certificationClasses = {
            'CourseButton--large': true
        };
        const certification = this.props.learningPlan.getIn(['certificationMap', segment]);
        const certificationCompletionList = this.props.learningPlan.getIn([
            'certificationCompletion',
            this.getPathwayCompletion().get('participantId')
        ]);

        // Update classes
        if (certification) {
            if (certificationCompletionList) {
                certificationClasses['is-complete'] = certificationCompletionList.includes(certification.get('itemCode'))
            }

            return <tr key={`${segment}certification`}>
                <td colSpan="2">
                    <div className={classnames(certificationClasses)} data-text={certification.get('itemName')}></div>
                </td>
            </tr>
        }

    },
    renderCertificationRow(course, key){
        var certificationClasses = classnames({
            'CourseButton--large': true,
            'is-complete': course.get('completed')
        });

        return <tr key={key}>
            <td colSpan="2">
                <div className={certificationClasses} data-text={course.get('workshopName')}></div>
            </td>
        </tr>
    },
    renderCourseRow(course, key){
        let learningPlan = this.getPathwayCompletion();
        // TODO: recertification dates
        // TODO: Nearly Expired
        return <tr key={key}>
            <td className="w75">{course.get('workshopName')}</td>
            <td className="t-center">{course.get('completed') ? <Icon hexCode="E199" className="t-success" />: ''}</td>
            <td className="w25">
                <CourseButton
                    course={course}
                    participantId={learningPlan.get('participantId')}
                    onClick={this.onCourseClick.bind(this, course)}
                    children={course.get}/>
            </td>
        </tr>;
    }
});

export default LearningPlan;
