import _ from 'lodash';
import CourseActivityModal from 'trc-client-core/src/course/CourseActivityModal';
import CourseProcess from 'trc-client-core/src/components/CourseProcess';
import GapReportGridCell from 'trc-client-core/src/report/GapReportGridCell';
import LearningPlanLink from 'trc-client-core/src/learningPlan/LearningPlanLink';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';
import NavigationActions from 'trc-client-core/src/global/NavigationActions';
import React from 'react';
import Time from 'trc-client-core/src/components/Time';
import Tooltip from 'trc-client-core/src/components/Tooltip';
import {IconPerson} from 'trc-client-core/src/components/Icons';
import {Link} from 'react-router';
import {technicalCareerPlan} from 'trc-client-core/src/constants/url';
import {
    E_LEARNING,
    FACE_TO_FACE,
    DOCUMENT,
    CERTIFICATION,
    ACHIEVEMENT
} from 'trc-client-core/src/constants/CourseType';


var GapReportGrid = React.createClass({
    displayName: 'GapReportGrid',
    mixins: [
        require('bd-stampy/mixins/ClassMixin.jsx'),
        require('trc-client-core/src/mixins/CourseMixin')
    ],
    propTypes: {
        data: React.PropTypes.array,
        type: React.PropTypes.string
    },
    getInitialState() {
        return {
            grouped: false,
            modalOpen: false,
            hideTooltip: true
        };
    },
    componentWillMount() {
        if(_.isPlainObject(this.props.data)) {
            this.setState({grouped: true});
        }
    },
    onCellClick(course, participant) {
        ModalManager.showModal(CourseActivityModal, {
            courseCode: course.courseCode,
            participantId: participant.participantId,
            pathwayId: this.props.pathwayId
        });
    },
    onMouseEnter() {
        this.setState({hideTooltip: false});
    },
    onMouseLeave() {
        this.setState({hideTooltip: true});
    },
    onCellHover(course, participant, cellOffset) {
        this.setState({
            tooltipCourse: course,
            tooltipParticipant: participant,
            tooltipOffset: cellOffset
        });
    },
    onModalClose() {
        NavigationActions.setQuery({modal: 'closed'});
    },
    filterRows(row) {
        if(this.props.filter) {
            return `${row.firstName}${row.lastName}`.toLowerCase().indexOf(this.props.filter.toLowerCase()) !== -1;
        }
        return true;
    },
    render() {
        var classes = this.createClassName('GapReportGrid').add('row2 hug-top');
        var data = this.props.data.filter(this.filterRows);
        if(this.props.groupBy) {
            data = _.groupBy(data, this.props.groupBy);
        }
        return (
            <div>
                <h2 className="hug-top">{this.props.title}</h2>
                <div
                    ref="main"
                    onMouseEnter={this.onMouseEnter}
                    onMouseLeave={this.onMouseLeave}
                    className={classes.className}>
                    {this.renderTooltip()}

                    <div className="GapReportGrid_fixed">{this.renderSingleOrGrouped(data, this.renderSideBarRow)}</div>
                    <div className="GapReportGrid_wrapper">
                        <div className="GapReportGrid_head">
                            {this.renderHeader(this.props.data[0].gapData)}
                        </div>
                        <div className="GapReportGrid_body" children={this.renderSingleOrGrouped(data, this.renderRow, '\t')} />
                    </div>
                </div>

            </div>
        );
    },
    renderTooltip() {
        if (this.state.tooltipCourse) {
            const {
                tooltipCourse: {completeDate, workshopName, completionProcess, eligible},
                tooltipParticipant: {firstName, lastName, jobPositionDesc}
            } = this.state;

            return <Tooltip hidden={this.state.hideTooltip} offset={this.state.tooltipOffset} rightLimit={this.refs.main.offsetWidth}>
                <strong>{workshopName}</strong>
                <div>{firstName} {lastName} - {jobPositionDesc}</div>
                {
                    (completeDate)
                        ? <em><CourseProcess data={completionProcess} />: <Time type="medium">{completeDate}</Time></em>
                        : <em>{eligible ? 'Eligible' : 'Ineligible'}</em>
                }
            </Tooltip>

        }
    },
    renderSingleOrGrouped(data, renderFunction, renderKey) {
        if(_.isArray(data)) {
            // Single Grouping
            return renderFunction(data);
        } else {
            // Multiple Groups
            return _(data).map((row, key) => {
                return [
                    <div className="GapReportGrid_label">{renderKey || key}</div>,
                    renderFunction(row)
                ];
            }).value();
        }
    },
    renderHeader(data) {
        return _.map(data, function(course, key){
            var ICON_MAP = {
                [E_LEARNING]: '\uE087',
                [CERTIFICATION]:'\uE075',
                [ACHIEVEMENT]:'\uE050',
                [DOCUMENT]: '\uE037',
                'DOCUMENTS': '\uE037',
                [FACE_TO_FACE]: '\uE004'
            }

            var props = {
                title: course.workshopName,
                className: "GapReportGrid_title"
            };

            let title = <span>
                <span data-icon={ICON_MAP[course.type]} className="Icon Icon-smallSize margin-right GapReportGrid_revertRotation"></span>
                <span>{course.itemAbbrName || course.workshopName}</span>
            </span>;

            var heading = <span {...props}>{title}</span>;
            if(course.type !== 'CERTIFICATION') {
                heading = <Link to={`/course/${course.courseCode}`} {...props}>{title}</Link>
            }

            return <div key={key} className={"GapReportGrid_square " + course.courseCode + " " + course.courseSection}>{heading}</div>;
        });
    },
    renderSideBarRow(data) {
        return data.map((person, key) => {
            var {participantId, firstName, lastName} = person;

            return <div key={key}>
                <Link to={`/portal/${participantId}`}>
                    <IconPerson size="small" className="margin-right05 shift-2"/>
                </Link>
                <LearningPlanLink
                    participantId={participantId}
                    learningPlan={this.props.learningPlan}
                    children={`${firstName} ${lastName}`}/>
            </div>;
        });
    },
    renderRow (data) {
        if(data.length === 0) {
            return <div className="InfoBox row">No data to display.</div>;
        }

        return _.map(data, (participant, key) => {
            var tds = _.map(participant.gapData, (course, subkey) => {
                return <GapReportGridCell
                    key={subkey}
                    course={course}
                    onClick={this.onCellClick.bind(this, course, participant)}
                    onHover={this.onCellHover.bind(this, course, participant)} />;
            });
            return <div key={key} className="GapReportGrid_row">{tds}</div>;
        });
    }
});

module.exports = GapReportGrid;
