import React from 'react';
import {reduxForm} from 'redux-form';
import {Map} from 'immutable';
import {Lifecycle} from 'react-router';
import CourseValidation from 'trc-client-core/src/course/CourseValidation';
import Fieldset from 'bd-stampy/components/Fieldset';
import FormError from 'trc-client-core/src/forms/FormError';
import IconSelect from 'trc-client-core/src/components/IconSelect';
import Input from 'bd-stampy/components/InputElement';
import InputRow from 'bd-stampy/components/InputRow';
import Loader from 'trc-client-core/src/components/Loader';
import Select from 'trc-client-core/src/components/Select';
import Textarea from 'bd-stampy/components/Textarea';
import ElearningTagInput from 'trc-client-core/src/course/ElearningTagInput';
import TechnicalTagForm from 'trc-client-core/src/course/TechnicalTagForm';
import DocumentTagForm from 'trc-client-core/src/course/DocumentTagForm';
import ModalManager from 'trc-client-core/src/Modal/ModalManager';
import ModalConfirm from 'trc-client-core/src/Modal/ModalConfirm';
import CourseTypes from 'trc-client-core/src/constants/CourseTypes';
import ErrorList from 'trc-client-core/src/components/ErrorList';

function getIcons() {
    var icons = ['MT', 'DT', 'PT', 'ST', '1F3E6', '1F4BC', 'E009', 'E025', 'E042', 'E043', 'E045', 'E049', 'E051', 'E052', 'E058', 'E059', 'E060', 'E067', 'E097', 'E100', 'E114', 'E115', 'E120', 'E138', 'E140', 'E149', 'E151', 'E156', 'E161', 'E210', 'E236', 'E245', 'E258', 'E259', 'E281', 'E283', 'E308', 'E320', 'E332', 'E333', 'E337', 'E350', 'E366', 'E372', 'E378', 'E458', 'E329', 'E087', 'E004', 'E293', 'E373', 'E255', 'E324', '1F6B2', 'E268', 'E270', 'E271'];
    return icons.reduce((reduction, value) => {
        reduction[value] = value;
        return reduction;
    }, {});
}

var IN_DEVELOPMENT = "IN DEVELOPMENT\nPlease contact Blue Flag";

var CourseEditForm = React.createClass({
    displayName: 'CourseEditForm',
    mixins: [Lifecycle],
    propTypes: {
        fields: React.PropTypes.object.isRequired
    },
    routerWillLeave() {
        if (this.props.dirty) {
            return 'You have unsaved information, are you sure you want to leave this page?';
        }
    },
    onChangeType(data) {
        var {type} = this.props.fields;
        var changeFunction = type.onChange.bind(this, data);
        if (type.value !== 'FACE_TO_FACE') {
            ModalManager.showModal(ModalConfirm, {
                title: 'Warning!',
                message: 'Are your sure you want to change the course type? Changing the Training Type after a course has been created can affect the way the course is handled in various parts of the TRC.',
                yes: 'Submit',
                onYes: changeFunction,
                no: 'Cancel'
            });
        } else {
            changeFunction();
        }
    },
    render() {
        const {
            submitting,
            errors,
            fields: {
                abbreviatedName,
                additionalResources,
                attendance,
                canWaitlist,
                company,
                courseCode,
                courseIcon,
                courseTrainer,
                departmentCategory,
                draft,
                duration,
                faceToFaceTag,
                id,
                learningOutcomes,
                overview,
                participantFeedBack,
                prerequisiteExpression,
                prerequisites,
                price,
                similarCourses,
                site,
                societyPoints,
                stream,
                trainingHours,
                type,
                viewableInList,
                workshopName
            }
        } = this.props;

        const similarCoursesOptions = this.props.similarCourses
            .reduce((reduction, course) => {
                return reduction.set(course.get('courseCode'), {
                    value: course.get('courseCode'),
                    label: `${course.get('courseCode')} - ${course.get('workshopName')}`
                });
            }, Map())
            .toArray();

        if (submitting) {
            return <Loader/>
        }

        function selectProps(obj) {
            return {
                ...obj,
                onBlur: obj.onBlur.bind(null, obj.value)
            }
        }

        function changeNumber(obj) {
            return {
                onChange: (ee, data) => obj.onChange(data.value),
                onBlur: (ee, data) => obj.onBlur(data.value)
            }
        }

        return <form>
                {!this.props.pristine ? <span className="Icon right t-red absolute top3 right3" data-icon={"\uE446"}></span> : null}
                <ErrorList {...this.props} />
                <Fieldset legend="General">

                    <input type="hidden" {...canWaitlist} />
                    <input type="hidden" {...draft} />
                    <input type="hidden" {...faceToFaceTag} />
                    <input type="hidden" {...site} />

                    <InputRow label="Workshop Name">
                        <Input {...workshopName} placeholder="e.g. Managing the Service Department"/>
                        <FormError {...workshopName} />
                    </InputRow>

                    <InputRow label="Abbreviated Name">
                        <Input {...abbreviatedName} placeholder="Create an abbreviated version to be used on Gap Reports (e.g. Mng Service Dept)"/>
                        <FormError {...abbreviatedName} />
                    </InputRow>

                    <InputRow label="Training Type">
                        <Select onChangeString {...selectProps(type)} onChange={this.onChangeType} options={CourseTypes} />
                    </InputRow>

                    <InputRow label="Stream">
                        <Select onChangeString {...selectProps(stream)}>
                            <option value="PRO">Professional</option>
                            <option value="TECH">Technical</option>
                        </Select>
                    </InputRow>

                    <InputRow label="Course Code">
                        <Input {...courseCode} placeholder="e.g. SAL1" onBlur={() => {}}/>
                        <FormError {...courseCode} />
                    </InputRow>

                    <InputRow label="Viewable In List">
                        <Input {...viewableInList} type="checkbox" name="viewableInList"/>
                    </InputRow>

                    <InputRow label="Can be Waitlisted">
                        <code className={`t-${(!!canWaitlist.value).toString()}`}>{(!!canWaitlist.value).toString()}</code>
                    </InputRow>


                    <InputRow label="Department Category">
                        <Select onChangeString multi {...selectProps(departmentCategory)}>
                            <option value="tech">Technical</option>
                            <option value="sales">Sales</option>
                            <option value="service">Service</option>
                            <option value="parts">Parts</option>
                            <option value="management">Management</option>
                            <option value="TMCA">TMCA/Internal</option>
                            <option value="body_paint">Body & Paint</option>
                        </Select>
                        <FormError {...departmentCategory} />
                    </InputRow>

                    {this.renderCourseTypeElements()}
                    {this.renderCourseStreamElements()}
                </Fieldset>


                <Fieldset legend="Admin">

                    <InputRow label="Prerequisites">
                        <Input {...prerequisiteExpression} placeholder="SPK1234 AND SPK5678" />
                    </InputRow>

                    <InputRow label="Prerequisite Description">
                        <Textarea {...prerequisites} placeholder="Extra text to explain the course's pre-requisites." />
                    </InputRow>

                    <InputRow label="Course Icon">
                        <IconSelect onChangeString {...courseIcon} icons={getIcons()} />
                        <FormError {...courseIcon} />
                    </InputRow>

                    <InputRow label="Training Company">
                        <Input {...company} placeholder="e.g. Human Synergy"/>
                    </InputRow>

                    <InputRow label="Id">
                        <Input {...id} disabled/>
                    </InputRow>

                    <InputRow label="Sales Society Points">
                        <Input {...societyPoints} placeholder="e.g. 2000"/>
                    </InputRow>

                    <InputRow label="Training Hours">
                        <Input {...trainingHours} type="number" placeholder="e.g. 5" {...changeNumber(trainingHours)}/>
                        <FormError {...trainingHours} />
                    </InputRow>
                </Fieldset>

                <Fieldset legend="Course Details">
                    <p>Please insert the text you would like to display on the website using Markdown, <br/> an easy to understand and learn web language. <a className="link" href="/#/admin/markdown">What is Markdown?</a></p>
                    <InputRow label="Course Overview">
                        <Textarea {...overview} placeholder={"e.g. \nThe Pro Technician Certification Exams are separated into seven key subjects being Electrical Systems, Engine..."} />
                    </InputRow>

                    <InputRow label="Learning Outcomes">
                        <Textarea {...learningOutcomes} placeholder={"e.g.\n* Understand the origins of Hybrid Vehicles \n* Understand the effects High Voltage has on the human body & the hybrid components that have this potential"}/>
                    </InputRow>

                    <InputRow label="Course Trainer">
                        <Input {...courseTrainer} placeholder="e.g. Andrew Ryan"/>
                    </InputRow>



                    <InputRow label="Duration">
                        <Input {...duration} placeholder="e.g. 1 Day"/>
                        <FormError {...duration} />
                    </InputRow>

                    <InputRow label="Price">
                        <Input {...price} placeholder="e.g. 495" />
                        <FormError {...price} />
                    </InputRow>

                    <InputRow label="Participant Feedback">
                        <Textarea {...participantFeedBack} placeholder={"e.g. \n> Great content, and the diverse roles of participants gave a good overview and opportunity to think how my role can help them provide a better experience for our clients."} />
                    </InputRow>

                    <InputRow label="Additional Resources">
                        <Textarea {...additionalResources} placeholder={IN_DEVELOPMENT} />
                        {/*<FileUploadForm  {...additionalResources} multiple/>*/}
                    </InputRow>

                    <InputRow label="Attendance">
                        <Textarea {...attendance} placeholder={"e.g.\n * All Sales Staff\n * Sales Managers"}/>
                    </InputRow>

                    <InputRow label="Associated Learning">
                        <Select
                            {...selectProps(similarCourses)}
                            onChangeString
                            multi
                            options={similarCoursesOptions}
                        />
                    </InputRow>

                </Fieldset>

                <ErrorList {...this.props} />

            </form>;
        },
        renderCourseTypeElements() {
            const {
                fields: {
                    type,
                    eLearningTag,
                    documentTag
                }
            } = this.props;

            switch(type.value) {
                case 'E_LEARNING':
                    return <ElearningTagInput {...eLearningTag} />;

                case 'DOCUMENT':
                    return <DocumentTagForm {...documentTag} />;
            }
        },
        renderCourseStreamElements() {
            const {
                fields: {
                    stream,
                    techTag
                }
            } = this.props;

            if (stream.value === 'TECH') {
                return <TechnicalTagForm {...techTag} />;
            }
        }
});

export const CourseEditFormFields = [
    'abbreviatedName',
    'additionalResources',
    'attendance',
    'canWaitlist',
    'company',
    'courseCode',
    'courseIcon',
    'courseTrainer',
    'departmentCategory',
    'documentTag.documents[].name',
    'documentTag.documents[].url',
    'draft',
    'duration',
    'eLearningTag',
    'faceToFaceTag',
    'id',
    'learningOutcomes',
    'overview',
    'participantFeedBack',
    'prerequisiteExpression',
    'prerequisites',
    'price',
    'proTag',
    'similarCourses',
    'site',
    'societyPoints',
    'stream',
    'techTag.category',
    'techTag.group',
    'techTag.streamCode',
    'trainingHours',
    'type',
    'viewableInList',
    'workshopName'
];

export default reduxForm({
    form: 'courseEditForm',
    destroyOnUnmount: false,
    validate: CourseValidation,
    fields: CourseEditFormFields
},
(state,props) => {
    return {
        initialValues: props.initialValues
    }
}
)(CourseEditForm);
