import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import content from 'global/constants/content'

import Form from 'react-toolkit/form'
import inputNames from 'common-fe/constants/input-names'
import investmentApproaches from 'common-fe/constants/investment-approaches'
import FormError from 'common-fe/utils/form-error'
import {sparsifyObj} from 'common-fe/utils'
import {renderLargeNumber} from 'common-fe/utils/render'

import Button from 'react-uikit/button'
import Course from './partials/course'
import StartingValue from './partials/starting-value'
import Icon from 'react-uikit/icon'
import InvestmentApproachInput from 'components/investment-approach-input'
import TextArea from 'react-uikit/textarea'
import TextInput from 'react-uikit/input-text'
import Tooltip from 'react-uikit/tooltip'

import {
    COURSE_ID_LENGTH,
    COURSE_PORTFOLIO_FUNDING_AMOUNTS,
    PORTFOLIO_NAME_MAX_LENGTH,
} from 'store/config'
import BEMModule from 'utils/bem'
import styles from './styles.scss'
const bem = new BEMModule(styles)

// -----------------------------------------------------------------------------
// NOTE: COMPONENT DEPRECATED
// -----------------------------------------------------------------------------

class ClassPortfolioCreationForm extends React.Component {
    static formName = 'class-portfolio-creation'

    static fundingOptions = COURSE_PORTFOLIO_FUNDING_AMOUNTS.map((amount) => ({
        label: renderLargeNumber(amount),
        value: amount,
    }))

    static defaultState = {
        data: {
            [inputNames.NAME]: '',
            [inputNames.STUDENT_ID]: '',
            [inputNames.COURSE_ID]: '',
            [inputNames.FUNDING_AMOUNT]:
                ClassPortfolioCreationForm.fundingOptions[0],
            [inputNames.INVESTMENT_APPROACH]: 'NONE',
            [inputNames.DESCRIPTION]: '',
        },
        error: {},
    }

    form = React.createRef()

    get initialState() {
        return {
            data: {
                ...ClassPortfolioCreationForm.defaultState.data,
                [inputNames.STUDENT_ID]: this.props.user.studentNumber || '',
            },
            error: {...ClassPortfolioCreationForm.defaultState.error},
        }
    }
    // Course ==================================================================
    fetchCourse = (courseId) => {
        this.props.getCourse({courseId})
    }

    get isCourseIdLength() {
        const {data} = this.props
        return data[inputNames.COURSE_ID].length === COURSE_ID_LENGTH
    }

    get course() {
        const {data, courses} = this.props
        return this.isCourseIdLength
            ? courses[data[inputNames.COURSE_ID].toLowerCase()]
            : null
    }

    get hasRegistered() {
        const {data, user} = this.props
        return this.course && user.courses.includes(data[inputNames.COURSE_ID])
    }
    get hasEnded() {
        return (
            this.course &&
            moment().isAfter(moment(this.course.endDate).endOf('day'))
        )
    }
    get courseErrors() {
        const {courses} = this.props
        if (
            this.isCourseIdLength &&
            courses.errors &&
            courses.errors.length > 0
        ) {
            return courses.errors
        }
        if (this.hasEnded) {
            return [{code: 'has-ended'}]
        }
        if (this.hasRegistered) {
            return [{code: 'has-registered'}]
        }

        return []
    }

    change = ({name, value}) => {
        if (name === inputNames.COURSE_ID) {
            let courseId = value.trim()
            courseId =
                courseId.length > COURSE_ID_LENGTH
                    ? courseId.substring(0, COURSE_ID_LENGTH)
                    : courseId

            // No change happened so no need to update
            if (this.props.data[name] === courseId) {
                return
            }

            // Fetch the course when the ID is the correct length
            courseId.length === COURSE_ID_LENGTH && this.fetchCourse(courseId)
            this.props.onChange && this.props.onChange({[name]: courseId})
            return
        }

        this.props.onChange && this.props.onChange({[name]: value})
    }

    createPortfolio = (data) => {
        const {createPortfolio, onError, onSubmit} = this.props

        if (!createPortfolio || !this.course) {
            return
        }

        const payload = sparsifyObj({
            [inputNames.COURSE_ID]: this.course.id,
            [inputNames.NAME]: data[inputNames.NAME],
            [inputNames.FUNDING_AMOUNT]:
                this.course.portfolioFundingAmount ||
                data[inputNames.FUNDING_AMOUNT].value,
            [inputNames.INVESTMENT_APPROACH]:
                investmentApproaches[data[inputNames.INVESTMENT_APPROACH]]
                    .value,
            [inputNames.DESCRIPTION]: data[inputNames.DESCRIPTION],
        })

        createPortfolio(payload, {redirect: true})
            .then((payload) => {
                onSubmit && onSubmit(payload)
            })
            .catch((err) => {
                if (!err.inlineErrors || !err.inlineErrors.length || !onError) {
                    return
                }

                const error = new FormError(
                    Object.keys(ClassPortfolioCreationForm.defaultState.data),
                    err.inlineErrors
                )

                onError && onError(error)
            })
    }

    render() {
        const {data, error, validateOnUpdate, onError} = this.props

        const nameClassNames = bem.classNames(
            'c-portfolio-creation-class__name'
        )
        const nameInputClassNames = bem.classNames(
            'c-portfolio-creation-class__name-input'
        )
        const helpIconClassNames = bem.classNames(
            'c-portfolio-creation-class__icon'
        )
        const studentNumInputClassNames = bem.classNames(
            'c-portfolio-creation-class__student-num-input'
        )
        const courseIdInputClassNames = bem.classNames(
            'c-portfolio-creation-class__course-id-input'
        )
        const sectionClassNames = bem.classNames(
            'c-portfolio-creation-class__section'
        )
        const labelClassNames = bem.classNames(
            'c-portfolio-creation-class__label'
        )
        const descriptionClassNames = bem.classNames(
            'c-portfolio-creation-class__description'
        )
        const approachClassNames = bem.classNames(
            'c-portfolio-creation-class__approach'
        )
        const approachLabelClassNames = bem.classNames(
            'c-portfolio-creation-class__approach-label'
        )
        const hrClassNames = bem.classNames('c-portfolio-creation-class__hr')
        const createButtonClassName = bem.classNames(
            'c-portfolio-creation-class__button'
        )

        return (
            <Form
                data={data}
                error={error}
                name={ClassPortfolioCreationForm.formName}
                submitOnEnter={false}
                validateOnUpdate={validateOnUpdate}
                onChange={this.change}
                onError={onError}
                onSubmit={this.createPortfolio}
            >
                <section className={nameClassNames}>
                    <label htmlFor={inputNames.NAME}>Portfolio Name</label>

                    <Form.Field
                        className={nameInputClassNames}
                        component={TextInput.Alternate}
                        maxLength={PORTFOLIO_NAME_MAX_LENGTH}
                        name={inputNames.NAME}
                        required
                    />
                </section>

                <section className={sectionClassNames}>
                    <div className={labelClassNames}>
                        <span data-tip="" data-for="studentNumberInfo">
                            Student Number
                            <Icon
                                name="tab-support"
                                className={helpIconClassNames}
                            />
                            <Tooltip id="studentNumberInfo">
                                <p>{content.studentNumberHelpText}</p>
                            </Tooltip>
                        </span>
                    </div>
                    <div>
                        <Form.Field
                            component={TextInput}
                            name={inputNames.STUDENT_ID}
                            placeholder="(optional)"
                            size="small"
                            className={studentNumInputClassNames}
                        />
                    </div>
                    <div className={labelClassNames}>
                        <span data-tip="" data-for="classIDInfo">
                            Challenge ID
                            <Icon
                                name="tab-support"
                                className={helpIconClassNames}
                            />
                        </span>
                        <Tooltip id="classIDInfo">
                            <p>{content.courseIdHelpText}</p>
                        </Tooltip>
                    </div>
                    <div>
                        <Form.Field
                            component={TextInput}
                            name={inputNames.COURSE_ID}
                            required
                            size="small"
                            className={courseIdInputClassNames}
                            placeholder=". . . . . . . . . . . . . . . . . . . . . . . ."
                        />
                    </div>
                </section>

                <Course course={this.course} errors={this.courseErrors} />

                <hr className={hrClassNames} />

                <StartingValue
                    disabled={!this.course}
                    name={inputNames.FUNDING_AMOUNT}
                    options={ClassPortfolioCreationForm.fundingOptions}
                    value={
                        this.course ? this.course.portfolioFundingAmount : null
                    }
                />

                <hr className={hrClassNames} />

                <section className={approachClassNames}>
                    <div>
                        <label
                            className={approachLabelClassNames}
                            htmlFor={inputNames.INVESTMENT_APPROACH}
                        >
                            Investment Approach
                        </label>
                        <Form.Field
                            component={InvestmentApproachInput}
                            name={inputNames.INVESTMENT_APPROACH}
                            required
                        />
                    </div>
                </section>
                <section className={descriptionClassNames}>
                    <label htmlFor={inputNames.DESCRIPTION}>Description</label>
                    <Form.Field
                        component={TextArea}
                        maxLength={500}
                        name={inputNames.DESCRIPTION}
                        placeholder="More about your portfolio’s purpose and approach"
                        resize
                    />
                </section>
                <Form.SubmitTrigger
                    render={({submit}) => (
                        <Button
                            className={createButtonClassName}
                            variant="primary"
                            text="Create"
                            onClick={submit}
                            disabled={!this.course}
                        />
                    )}
                />
            </Form>
        )
    }
}

ClassPortfolioCreationForm.propTypes = {
    courseIdLength: PropTypes.number,
    courses: PropTypes.object,
    createPortfolio: PropTypes.func,
    data: PropTypes.shape({
        [inputNames.NAME]: PropTypes.string,
        [inputNames.STUDENT_ID]: PropTypes.string,
        [inputNames.COURSE_ID]: PropTypes.string,
        [inputNames.FUNDING_AMOUNT]: PropTypes.object,
        [inputNames.INVESTMENT_APPROACH]: PropTypes.string,
        [inputNames.DESCRIPTION]: PropTypes.string,
    }),
    error: PropTypes.shape({
        [inputNames.NAME]: PropTypes.string,
        [inputNames.STUDENT_ID]: PropTypes.string,
        [inputNames.COURSE_ID]: PropTypes.string,
        [inputNames.FUNDING_AMOUNT]: PropTypes.string,
        [inputNames.INVESTMENT_APPROACH]: PropTypes.string,
        [inputNames.DESCRIPTION]: PropTypes.string,
    }),
    getCourse: PropTypes.func,
    user: PropTypes.shape({
        studentNumber: PropTypes.string,
        courses: PropTypes.Array,
    }),
    validateOnUpdate: PropTypes.bool,
    onChange: PropTypes.func,
    onError: PropTypes.func,
    onSubmit: PropTypes.func,
}

ClassPortfolioCreationForm.defaultProps = {
    data: {...ClassPortfolioCreationForm.defaultState.data},
    error: {...ClassPortfolioCreationForm.defaultState.error},
    validateOnUpdate: true,
}

export default ClassPortfolioCreationForm
