import React from 'react';
import _ from 'lodash';
import Reflux from 'reflux';
import {History} from 'react-router';
import RegistrationStore from 'trc-client-core/src/course/RegistrationStore';
import RegistrationActions from 'trc-client-core/src/course/RegistrationActions';
import SoRegistrationBox from 'trc-client-core/src/course/SoRegistrationBox';
import Markdown from 'trc-client-core/src/components/Markdown';

import CancellationPolicy from 'trc-client-core/src/copy/_partials/CancellationPolicy';

import Grid from 'trc-client-core/src/components/Grid';
import Col from 'trc-client-core/src/components/Col'; 
import Label from 'bd-stampy/components/Label';
import Textarea from 'bd-stampy/components/Textarea';
import Input from 'bd-stampy/components/InputElement';
import Button from 'bd-stampy/components/Button'; 

import Site from 'trc-client-core/src/constants/Site';
import UserStore from 'trc-client-core/src/user/UserStore';

function ifEmpty(message) {
    return function (val) {
        if (_.isEmpty(val)) { 
            return message;
        }
    };
}

var ConfirmRegistrationView = React.createClass({
    displayName: 'ConfirmRegistrationView',
    mixins: [
        History, 
        require('trc-client-core/src/course/RegistrationMixin'),
        require('reflux-immutable/StoreMixin'),
        require('bd-stampy/mixins/FormMixin'),
        Reflux.listenTo(RegistrationStore, 'onStoreChange')
    ],
    getStoreState() {        
        return {
            registrations: RegistrationStore.get('registrations'),
            cancellations: RegistrationStore.get('cancellations'),
            soData: RegistrationStore.get('soData'),
            candidates: RegistrationStore.get('candidates')
        };
    },
    componentWillMount() {
        if(!RegistrationStore.get('registrations')) {
            this.history.pushState(null, `/course/${this.props.params.id}`);
        }
        this.onStoreChange();
    },
    validators: {
        accept: (value) => {
            if (!value) {
                return 'You must accept the terms and conditions.';
            }
        },
        reason: ifEmpty('You must supply a reason for unenrolment.')
    },
    onSubmitForm() {
        if(this.FormMixin_isValid() || this.state.cancellations.size === 0) {
            RegistrationActions.enrol({
                ...this.state.formData,
                courseCode: this.props.params.id
            });
        }
    },
    onCancel(){
        this.history.pushState(null, `/course/${this.props.params.id}`);
    },
    render() {
        return (
            <div>
                <h1>Confirm Updated Enrolment</h1>
                <Grid>
                    <Col>
                        {this.renderEnrollemnts()}
                    </Col>
                    <Col>
                        {this.renderCancellationPolicy()}
                    </Col>
                </Grid>
                <div className="ButtonBar margin-top2">
                    <Button modifier="grey" onClick={this.onCancel}>Cancel</Button>
                    <Button onClick={this.onSubmitForm}>Lodge Enrolments</Button>
                </div>
            </div>
        );
    },
    renderEnrollemnts() {
        var {registrations, soData, candidates, cancellations} = this.state;

        if(registrations) {
            return soData.sortBy(so => so.get('soStartDate')).map(soItem => {
                var soId = soItem.get('soId').toString();
                if(registrations.get(soId) || (cancellations.size && cancellations.get(soId))) {
                    return <SoRegistrationBox 
                        key={soId}
                        type="confirm"
                        registrations={registrations.get(soId)}
                        cancellations={cancellations.get(soId)}
                        allRegistrations={registrations.toList().flatten(true).concat(cancellations.toList().flatten(true))}
                        candidates={candidates}
                        soData={soItem}
                    />;
                }
            }).toList().toJS();            
        }        
    },
    renderCancellationPolicy() {
        if(!this.state.cancellations.size) {
            return null;
        }

        var checkBoxError;

        if(this.state.formErrors.accept) {
            checkBoxError = <div className="error">{this.state.formErrors.accept}</div>;
        }

        return <div>
            <Markdown html={CancellationPolicy} context={Site[UserStore.get('site')]}></Markdown>
            <div className="margin-top">
                <Label label="">
                    <Input 
                        name="accept" 
                        type="checkbox" 
                        className="inline"
                        modifier={(checkBoxError) ? 'error' : null}
                        onChange={this.FormMixin_onFormChange}
                        defaultChecked={this.state.viewableInList} 
                    />
                    <span>I accept the Terms and Conditions</span>
                </Label>
                {checkBoxError}

                <h3>Reason for Unenrolling</h3>
                <Textarea 
                    name="reason" 
                    onChange={this.FormMixin_onFormChange} 
                    error={this.state.formErrors.reason}
                />
            </div>
        </div>;
    }
});

module.exports = ConfirmRegistrationView;
