import Loader from 'trc-client-core/src/components/Loader';
import CourseButton from 'trc-client-core/src/components/CourseButton';
import React from 'react';
import moment from 'moment';
import UserStore from 'trc-client-core/src/user/UserStore';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import {List} from 'immutable';
import {vehiclesRequest} from 'trc-client-core/src/product/ProductActions';
import ProductLearningPlanFaceToFace from 'trc-client-core/src/product/ProductLearningPlanFaceToFace';
import {staticUrl} from 'trc-client-core/src/constants/url';
import Markdown from 'trc-client-core/src/components/Markdown';
import Heading from 'trc-client-core/src/components/Heading';
import ErrorMessage from 'trc-client-core/src/components/ErrorMessage';
import HeroText from 'trc-client-core/src/components/HeroText';
import CourseActivityModal from 'trc-client-core/src/course/CourseActivityModal';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';

const SEGMENT_NAMES = {
    'Cars': 'Cars',
    'Hybrid': 'Hybrid',
    'SUV_4WD': 'SUV & 4WD',
    'UTES_VANS': 'Utes & vans',
    'Performance': 'Performance',
    'Additional Content': UserStore.get('site') === 'TOYOTA' ? 'The Toyota Edge' : 'Additional Content'
}

var ProductPathway = React.createClass({
    displayName: 'ProductPathway',
    propTypes: {
        singleId: React.PropTypes.string
    },
    componentWillMount() {
        this.props.dispatch(vehiclesRequest());
    },
    onCourseClick(course) {
        ModalManager.showModal(CourseActivityModal, {
            courseCode: course.get('courseCode'),
            participantId: this.props.learningPlan.getIn(['pathwayCompletion', 0, 'participantId'])
        });
    },
    getGapData() {
        return this.props.learningPlan.getIn(['pathwayCompletion', 0, 'gapData'])
    },
    render() {
        var {learningPlan, error, vehicles} = this.props;

        if(error) {
            return <em className="InfoBox">{error.body.message}</em>
        }

        if(!learningPlan && !UserStore.get('participantId')){
            return <em className="InfoBox">{`This user doesn't have a Product Plan`}</em>
        }
        
        if(!learningPlan || !vehicles){
            return <Loader />;
        }

        if(learningPlan.get('pathwayCompletion').size === 0 ){
            return <em className="InfoBox">{`This user doesn't have a Product Plan`}</em>
        }

        if(!learningPlan.get('pathwayCompletion').size) {
            return <ErrorMessage message="The current user does not have a Product Learning Plan" />
        }

        return this.renderProductPathway();
    },
    getCompletionPercentage(){
        return this.props.learningPlan
            .getIn(['pathwayCompletion', 0, 'gapData'])
            .map(course => course.get('completed'))
            .reduce((reduction, value, key, list) => (value) ? Math.floor(reduction + 100 / list.size) : reduction, 0);
    },
    renderProductPathway(){
        var body = (this.props.singleId) ? this.renderSingleRow() : this.renderWholePathway();
        return <div>
            {this.renderHeader()}
            <table className="Table Table-tight">
                {this.renderTableHead()}
                <tbody>{body}</tbody>
            </table>
            {!this.props.singleId ? <ProductLearningPlanFaceToFace participantId={this.props.participantId}/> : null}
            {this.renderFooter()}
        </div>;
    },
    renderHeader() {
        var percentage = this.getCompletionPercentage();
        var participant = this.props.learningPlan.getIn(['pathwayCompletion', 0]) || UserStore;

        if (this.props.singleId) {
            return <Heading level="h2" title="Product Training Plan" subtitle={participant.get('firstName') + ' ' + participant.get('lastName')}/>;
        }

        return <div className="margin-bottom2">
            <HeroText className="margin-left right" colorPercentage={percentage}>{percentage}%</HeroText>
            <h1>
                <span>Product Training Plan </span>
                <div className="t-muted">{`${participant.get('firstName')} ${participant.get('lastName')} `}</div>
            </h1>
            <Markdown html={this.props.learningPlan.get('headerText')} />
        </div>
    },
    renderTableHead() {
        var extraHead = (this.props.singleId) ? null : <th></th>;
        return <thead className="t-center">
            <tr>
                {extraHead}
                {extraHead}
                <th className="t-center w25"><div data-icon={String.fromCharCode(9729)} className="Icon"/> eLearning</th>
                <th className="t-center w25"><div data-icon={String.fromCharCode(57399)} className="Icon"/> Product Guide</th>
                <th className="t-center w25"><div data-icon={String.fromCharCode(57353)} className="Icon"/> Training Video</th>
            </tr>
        </thead>
    },
    renderSingleRow() {
        var row = this.getGapData()
            .filter(course => course.get('segment') === this.props.singleId);

        return this.renderRow(row, this.props.singleId);
    },
    renderWholePathway() {
        var vehicleSegments = this.props.vehicles
            .groupBy(ii => ii.getIn(['segments', 0]));


        var segmentedGapData = this.getGapData()
            .groupBy(ii => ii.getIn(['segment']))

        const renderRows = (ii, key) => {
            return this.renderRow(segmentedGapData.get(key), key);
        }

        return vehicleSegments
            .map((segment, segmentKey) => {
                return segment
                    .sortBy((course, vehicleName) => vehicleName)
                    .map(renderRows)
                    .toList()
                    .unshift(this.renderBar(segmentKey));
            })
            .toList()
            .update(rows => {
                var extraCourses = this.getGapData()
                    .filter(ii => !this.props.vehicles.has(ii.get('segment')))
                    .groupBy(ii => ii.get('segment'))
                    .map(renderRows);

                if(extraCourses.size) {
                    return rows
                        .push(this.renderBar('Additional Content'))
                        .concat(extraCourses)
                }

                return rows;
            })
            .toJS();
    },
    renderBar(segmentKey) {
        return <tr key={`${segmentKey}-segment`}>
            <td colSpan="5">
                <div className="Bar Bar-product margin-top margin-bottom">{SEGMENT_NAMES[segmentKey]}</div>
            </td>
        </tr>
    },
    renderRow(courses, vehicleName) {
        courses = courses || List();
        var thumbnail;
        var title;
        const vehicle = this.props.vehicles.get(vehicleName) || courses;
        const launchDate = vehicle.get('launchDate')
            ? '-' + moment(new Date(vehicle.get('launchDate'))).format('YYYY_MM')
            : '';

        const elearning = courses.find(inWorkshopName('elearning module'));
        const dealerProductGuide = courses.find(inWorkshopName('dpg'));
        const trainingVideo = courses.find(inWorkshopName('video'));

        function inWorkshopName(str) {
            return (course) => course.get('workshopName').toLowerCase().indexOf(str) !== -1;
        }

        function vehicleLink(courses, vehicles, vehicleName, children) {
            if (vehicles.get(vehicleName)) {
                return <Link to={`/product/vehicles/${vehicleName}`}>{children}</Link>;
            } else {
                return children;
            }
        }

        const renderVehicleLink = vehicleLink.bind(this, courses, this.props.vehicles, vehicleName);

        if(!this.props.singleId) {
            thumbnail = <td className="w00">
                {renderVehicleLink(<img
                    src={staticUrl(`img/ui/product/vehicles/${UserStore.get('site')}/${vehicleName.toLowerCase().replace(/ /g, '')}${launchDate}.jpg`)}
                    className="inline"
                    height="32"
                />)}
            </td>;
            title = <td className="w15">{renderVehicleLink(vehicleName)}</td>;
        }

        return <tr key={vehicleName}>
            {thumbnail}
            {title}
            <td><CourseButton onClick={this.onCourseClick.bind(this, elearning)} course={elearning} /></td>
            <td><CourseButton onClick={this.onCourseClick.bind(this, dealerProductGuide)} course={dealerProductGuide} /></td>
            <td><CourseButton onClick={this.onCourseClick.bind(this, trainingVideo)} course={trainingVideo} courseType="TRAININGVIDEO"/></td>
        </tr>
    },
    renderFooter() {
        if(this.props.singleId) {
            return <Link className="cta" to="/portal/learning-plan/product_training_plan">View full Product Training Plan</Link>;
        }

        return <Markdown html={this.props.learningPlan.get('footerText')} />
    }
});

const connectWithVehicles = connect((state, props) => ({
    learningPlan: props.learningPlan,
    vehicles: state.product.get('vehicles')
}));

export default connectWithVehicles(ProductPathway);
