
import React from 'react';
import _ from 'lodash';
import Reflux from 'reflux';
import moment from 'moment';
import {Link} from 'react-router';


import UrlStore from 'bd-stampy/utils/UrlStore';
import Table from 'bd-stampy/components/Table';
import RequiredRoleSelect from 'trc-client-core/src/requiredRoles/RequiredRoleSelect';
import RegionSelect from 'trc-client-core/src/components/RegionSelect';
import Select from 'trc-client-core/src/components/Select';
import CurriculumBadges from 'trc-client-core/src/learningPlan/CurriculumBadges';

import {Tab, TabView, TabContent} from 'bd-stampy/components/Tabs';
import Grid from 'trc-client-core/src/components/Grid';
import Col from 'trc-client-core/src/components/Col';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';
import RequiredRoleReportInfo from '../Modal/ModalRequiredRoleReportInfo';

import Loader from 'trc-client-core/src/components/Loader';

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

import DataTable from 'bd-stampy/components/DataTable';

function fullName(participant) {
    return `${participant.firstName} ${participant.lastName}`;
}

var RequiredRolesReport = React.createClass({
    displayName: 'RequiredRolesReport',
    mixins: [
        Reflux.listenTo(RequiredRolesStore, 'onStoreUpdate')
    ],
    getStoreState() {
        return {
            reportDetails : RequiredRolesStore.getAdminReport(),
            roles : RequiredRolesStore.getRoles()
        };
    },
    getInitialState() {        
        return {
            ...this.getStoreState(),
            fetching: true
        };
    },
    componentDidMount() { 
        this.getData(this.props);
    },
    componentWillReceiveProps(nextProps) {
        // var nextQuery = nextProps.location.query;
        // var {query} = this.props.location;
        // console.log(this.props, nextProps);
        if(this.props.location.search !== nextProps.location.search) {
            this.getData(nextProps);
        }  
    },
    getData(props) { 
        var {roleId, regionCode} = props.location.query;
        this.setState({fetching: true });
        RequiredRolesActions.fetchAllRequiredRoles();

        var prom = RequiredRolesActions.fetchAdminReport({
            roleId: roleId,
            regionCode: regionCode || 'ALL_REGIONS'
        });
        prom.then(
            () => this.setState({fetching: false}), 
            (error) => console.error('[ERROR]', error)
        );
    },
    onChange(e, details) {
        if(this.props.onChange) {
            this.props.onChange(e, details);
        }
    },
    onStoreUpdate() {
        this.setState(this.getStoreState());
    },
    onDecision(participantId, roleId, roleStatus){
        var {regionCode} = this.props.location.query;
        RequiredRolesActions.decision({
            status: roleStatus,
            roleId: roleId,
            participantId: participantId,
            regionCode: regionCode
        });
    },
    showInfo() {
        ModalManager.showModal(RequiredRoleReportInfo);
    },
    render() {
        return (
            <div>
                <h1>Report <span className="t-muted">Required Roles</span><Icon name="circleinfo" className="push-left" onClick={this.showInfo}/></h1>
                {this.renderFilters()}
                {this.renderReportTable()}
            </div>
        );
    },
    renderReportTable() {
        if(this.props.location.query.roleId){
            return <div>
                <TabView transition={false} >
                    <Tab>Pending</Tab>
                    <TabContent>
                       {this.renderReportDataPending(this.state.reportDetails.pending)}
                    </TabContent>

                    <Tab>Approved</Tab>
                    <TabContent>
                        {this.renderReportTableApproved(this.state.reportDetails.approved)}
                    </TabContent>

                    <Tab>Yet To Nominate</Tab>
                    <TabContent>
                       {this.renderReportDataYetToNominate(this.state.reportDetails.yetToNominate)}
                    </TabContent>
                </TabView>
            </div>;
            
        } else {
            return <em className="InfoBox">No Data to display</em>;
        }
    },
    renderFilters(){
        if(this.state.roles.length === 0){
            return <Loader />;
        }
        return (
            <Grid modifier="tight">
                <Col width={4}>
                    <RequiredRoleSelect roles={this.state.roles} value={this.props.location.query.roleId} />
                </Col>
                <Col width={3}>
                    <RegionSelect value={this.props.location.query.regionCode || 'ALL_REGIONS'} />
                </Col>
                <Col>
                </Col>
            </Grid>
        );
    },
    renderReportTableApproved(data){ 
        return this.renderTable(data, [{
            heading: 'Name/Job Description', 
            filter: (item) => fullName(item.participantData).toLowerCase(), 
            width: '20%',
            render: (item) => <div>
                <Link to={`/portal/${item.participantData.participantId}`} className="readmore">{fullName(item.participantData)}</Link>
                <br/>
                {item.participantData.jobPositionDesc}
            </div>
        }, {
            heading: 'Dealership',
            filter: (item) => item.participantData.dealerName,
            width: '13%'
        }, {
            heading: 'Nominating Manager',
            filter: (item) => fullName(item.manager),
            width: '13%'
        }, {
            heading: 'Nomination Date',
            filter: 'nominationDate',
            render: (item) => (item.nominationDate !== null) ? moment(new Date(item.nominationDate )).format('YYYY-MM-DD') : '-',
            width: '15%'
        }, {
            heading: 'Approved By',
            filter: (item) => fullName(item.decisionManager),
            width: '15%'
        }, {
            heading: 'Approval Date',
            filter: 'approvalDate',
            render: (item) => moment(new Date(item.approvalDate || 0)).format('DD MMM YYYY')
        }]);        
    },
    renderReportDataPending(data){ 
        return this.renderTable(data, [{
            heading: 'Name/Job Description', 
            filter: (item) => fullName(item.participantData).toLowerCase(), 
            width: '20%',
            render: (item) => <div>
                <Link to={`/portal/${item.participantData.participantId}`} className="readmore">{fullName(item.participantData)}</Link>
                <br/>
                {item.participantData.jobPositionDesc}
            </div>
        }, {
            heading: 'Dealership',
            filter: (item) => item.participantData.dealerName,
            width: '20%'
        }, {
            heading: 'Nominating Manager',
            filter: (item) => fullName(item.manager),
            width: '15%'
        }, {
            heading: 'Nomination Date',
            filter: 'nominationDate',
            render: (item) => (item.nominationDate !== null) ? moment(new Date(item.nominationDate )).format('YYYY-MM-DD') : '-',
            width: '15%'
        }, {
            heading: 'Curriculum',
            filter: (item) => fullName(item.participantData),
            render: item => <CurriculumBadges
                careerData={this.state.reportDetails.careerPlans[item.participantData.participantId]}
                user={item.participantData} all={true}
            />,
            width: '30%'
        }, {
            heading: 'Action',
            filter: (item) => fullName(item.participantData),
            render: (item) => <div>
                <a key="APPROVED" onClick={this.onDecision.bind(this, item.participantData.participantId, item.roleId, "APPROVED")} className="Button Button-small Button-edit w100" >Approve</a>
                <a key="DENIED" onClick={this.onDecision.bind(this, item.participantData.participantId, item.roleId, "DENIED")} className="Button Button-small w100" >Deny</a>
            </div>
        }]);
    },
    
    renderReportDataYetToNominate(data){ 
        return this.renderTable(data, [{
            heading: 'Name', 
            filter: 'name'
        }, {
            heading: 'Dealership Code',
            filter: 'code'
        }]);
    },
    renderTable(data, schema, emptyText) {
        if(!data || this.state.fetching) {
            return <Loader />;
        }

        if(data.length === 0 ){
            return <em className="InfoBox">No Data to display</em>;
        }        

        return <DataTable
            schema={schema} 
            data={data} 
            modifier="data"
        />;

    } 
});

module.exports = RequiredRolesReport;
