import React from 'react';
import Reflux from 'reflux';
import _ from 'lodash';
import moment from 'moment';
import Grid from 'trc-client-core/src/components/Grid';
import Col from 'trc-client-core/src/components/Col';

import RequiredRolesActions from 'trc-client-core/src/requiredRoles/RequiredRolesActions';
import RequiredRolesStore from 'trc-client-core/src/requiredRoles/RequiredRolesStore';

import Table from 'bd-stampy/components/Table';
import Loader from 'trc-client-core/src/components/Loader';
import Button from 'bd-stampy/components/Button';
import Select from 'bd-stampy/components/Select';


var RequiredRoleDetail = React.createClass({
    displayName: 'RequiredRoleDetail',
    propTypes: {
        single: React.PropTypes.bool,
        role: React.PropTypes.object
    },
    mixins: [
        require('bd-stampy/mixins/FormMixin'),
        require('reflux-immutable/StoreMixin'),
        Reflux.listenTo(RequiredRolesStore, 'onStoreChange')
    ],
    getStoreState() {
        return {
            toggleItemRole: false,
            nominateLoading: RequiredRolesStore.get('nominateLoading')
        };
    },
    toggleRole: function() {
        this.setState({toggleItemRole: !this.state.toggleItemRole});
    },
    onNominate(){
        RequiredRolesActions.nominate({
            roleId: this.props.item.role.id,
            participantId: this.state.formData.nominateStaff
        })
        .then(
            () => {
                this.setState({
                    error: null
                });
            },
            (error) => {
                this.setState({
                    nominateLoading: false,
                    error: error.body.message
                })
            }
        );
        this.setState({toggleItemRole: true});
    },
    onReNominate(id){
        RequiredRolesActions.renominate({
            roleId: this.props.item.role.id,
            participantId: id
        });
        this.setState({toggleItemRole: true});
    },
    onRemove(id){
        RequiredRolesActions.remove({
            roleId: this.props.item.role.id,
            participantId: id
        });
        this.setState({toggleItemRole: true});
    },
    render: function () {
        if(!this.props.item){
            return <Loader></Loader>;
        }
        var toggleHead = '';
        var toggleContent = '';
        var toggle = this.state.toggleItemRole ? ' is-active' : ' ';
        var role = this.props.item.role;

        if(!this.props.singleRole && this.props.item.nominees.length > 1){
            toggleHead = ' Toggle';
            toggleContent = 'Toggle_content';
        }

        var nominateStatusMessage;
        if(this.state.error) {
            nominateStatusMessage = <div className="InfoBox">{this.state.error}</div>;
        }
        if(this.state.nominateLoading) {
            nominateStatusMessage = <Loader/>;
        }


        return <div>
            <h2 className={`${toggleHead} ${toggle}`}>{role.name}s</h2>
            <div className={toggleContent}>
                {this.renderNominatedStaff()}
                {nominateStatusMessage}
                {this.renderRoleNominationList()}
            </div>
        </div>;
    },
    renderNominatedStaff: function (){
        if(this.props.item.nominees.length === 0) {
            return <div className="InfoBox">You currently have no staff in this Required Role, please nominate a staff member as soon as possible.</div>;
        }
        return this.props.item.nominees.map((roleNominee, key) => {
            var {manager, participantData, status} = roleNominee;
            var statusClass = 't-yellow';
            var approvalManager = '-';
            var approvalDate = '-';
            var renominateBtn;

            switch(status){
                case "APPROVED":
                    statusClass = "t-green";
                    approvalManager = `${roleNominee.decisionManager.firstName} ${roleNominee.decisionManager.lastName}`;
                    approvalDate = moment(new Date(roleNominee.approvalDate || 0)).format('DD-MM-YYYY');
                    break;
                case "DENIED":
                    statusClass = "t-red";
                    renominateBtn = <Button onClick={this.onReNominate.bind(this, participantData.participantId)}>Re-Nominate</Button>;
                    break;
            }

            return (
                <Grid key={key} className="Widget row">
                    <Col width={3}>
                        <h3 className="hug">{`${participantData.firstName} ${participantData.lastName}`}</h3>
                        <div className={statusClass}>{status}</div>
                    </Col>
                    <Col>
                        <Table modifier="tight" className="hug">
                            <tr>
                                <td>Email:</td>
                                <td><a className="link t-transformNone" href={`mailto:${roleNominee.participantData.emailAddress}`}>{roleNominee.participantData.emailAddress}</a></td>
                            </tr>
                            <tr>
                                <td>Nominating Manager:</td>
                                <td>{`${manager.firstName} ${manager.lastName}`}</td>
                            </tr>
                            <tr>
                                <td>Approved By:</td>
                                <td>{approvalManager}</td>
                            </tr>
                            <tr>
                                <td>Commencement Date:</td>
                                <td>{approvalDate}</td>
                            </tr>
                        </Table>
                        <div className="right margin-top">
                           <Button modifier="grey" onClick={this.onRemove.bind(this, participantData.participantId)}>Remove</Button>
                           {renominateBtn}
                        </div>
                    </Col>
                </Grid>
            );
        });
    },
    renderRoleNominationList: function () {
        var eligibleStaffList = _(this.props.item.eligibleStaff)
            .filter((staff) => !_.find(this.props.item.nominees, (item) => item.participantData.participantId === staff.participantId))
            .map((eligibleOption, key) => <option key={key} value={eligibleOption.participantId}>{`${eligibleOption.firstName} ${eligibleOption.lastName}`}</option>)
            .value();

        eligibleStaffList.unshift(<option key="choose" value="">Choose Nominee</option>);
        return (
            <Grid className="padding">
                <Col>
                    <h3 className="hug-top">Eligible Staff:</h3>
                </Col>
                <Col width={7}>
                    <Select name="nominateStaff" onChange={this.FormMixin_onFormChange}>{eligibleStaffList}</Select>
                </Col>
                <Col>
                    <Button className="w100" onClick={this.onNominate} disabled={!this.state.formData.nominateStaff}>Nominate</Button>
                </Col>
            </Grid>
        );
    }
});
module.exports = RequiredRoleDetail;
