import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import isEqual from 'lodash.isequal'

import Button from 'react-uikit/button'
import Form from 'react-uikit/form'
import Debug from 'common-fe/utils/debug'
import SchoolClient from 'common-fe/clients/school'
import inputNames from 'common-fe/constants/input-names'
import FormError, {reason} from 'common-fe/utils/form-error'
import {validateInput} from 'common-fe/utils/validation'
import {renderLargeNumber} from 'common-fe/utils/render'
import {sparsifyObj} from 'common-fe/utils'
import {
    benchmarkOptions,
    fundingOptions,
    getSumOfRankingWeights,
} from '../../forms/course-creation-form/helpers'
import {COURSE_PORTFOLIO_FUNDING_AMOUNTS} from 'store/config'

import ChallengeCustomization from '../course-creation-form/partials/challenge-customization'

import BEMModule from 'utils/bem'
import styles from '../course-creation-form/styles.scss'
const bem = new BEMModule(styles)

// TODO: change end date to be end of day if updated
class CourseSettingsForm extends React.Component {
    static formName = 'class-settings'

    static defaultState = {
        data: {
            [inputNames.COURSE_BENCHMARK]: benchmarkOptions[1],
            [inputNames.COURSE_CODE]: '',
            [inputNames.COURSE_DESCRIPTION]: '',
            [inputNames.COURSE_END_DATE]: [],
            [inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE]: '20',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS]: '15',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES]: '5',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES]: '30',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS]: '5',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES]: '25',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS]: '10',
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS]: '5',
            [inputNames.COURSE_INSTITUTION]: {label: '', value: ''},
            [inputNames.COURSE_MESSAGE]: '',
            [inputNames.COURSE_NAME]: '',
            [inputNames.COURSE_START_DATE]: [],
            [inputNames.COURSE_STARTING_VALUE]: fundingOptions[2],
            [inputNames.COURSE_ENGAGEMENT_IS_HOLDINGS]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_MAX_CASH_PERCENTAGE]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_RATIONALES]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_TRADES]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_TRADES_BONDS]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_TRADES_EQUITIES]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_TRADES_OPTIONS]: false,
            [inputNames.COURSE_ENGAGEMENT_IS_TRADES_SHORTS]: true,
            [inputNames.COURSE_ENGAGEMENT_IS_TRACKING]: true,
            [inputNames.IS_TEAM_PORTFOLIOS]: false,
            [inputNames.RANKING_WEIGHT_DIVERSIFICATION]: 0,
            [inputNames.RANKING_WEIGHT_ENGAGEMENT]: 0,
            [inputNames.RANKING_WEIGHT_RETURN]: 0,
            [inputNames.RANKING_WEIGHT_SHARPE_RATIO]: 0,
            [inputNames.RANKING_WEIGHT_VOLATILITY]: 0,
            [inputNames.RESTRICT_DAY_TRADING]: false,
            [inputNames.IS_TEAM_PORTFOLIOS]: false,
        },
    }

    static getFlags = (type) => {
        const flags = {
            holdings: [
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_HOLDINGS,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS,
                },
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_MAX_CASH_PERCENTAGE,
                    key: inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE,
                },
            ],
            rationales: [
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_RATIONALES,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES,
                },
            ],
            totalTrades: [
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_TRADES,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES,
                },
            ],
            // Trades by security type
            trades: [
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_TRADES_BONDS,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS,
                },
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_TRADES_EQUITIES,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES,
                },
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_TRADES_OPTIONS,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS,
                },
            ],
            // Trades by action type
            tradesAction: [
                {
                    flag: inputNames.COURSE_ENGAGEMENT_IS_TRADES_SHORTS,
                    key: inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS,
                },
            ],
        }

        // return a subsection or all of them
        return flags[type] || Object.values(flags).flatten()
    }

    form = React.createRef()

    state = {
        currentPageIndex: 0,
        isFormValid: false,
    }

    componentDidMount() {
        const {schoolId} = this.props.course

        if (schoolId) {
            return SchoolClient.getSchool({schoolId})
                .then((school) => {
                    this.onChange({
                        name: inputNames.COURSE_INSTITUTION,
                        value: {label: school.name, value: schoolId},
                    })
                })
                .catch((err) =>
                    Debug.log(
                        `Could not retrieve school with id ${schoolId} - error: ${err}`
                    )
                )
        }

        return null
    }

    componentDidUpdate({data: previousData}) {
        const {data} = this.props

        if (isEqual(data, previousData)) {
            return false
        }

        // Check to see if the form is missing values that are needed to submit it
        const isInvalid = Object.keys(
            CourseSettingsForm.defaultState.data
        ).some((key) => {
            // Ignore course challenge type
            if (key === inputNames.COURSE_CHALLENGE_TYPE) {
                return false
            }

            const value = data[key]

            // If the value is an array, check if it has any items in it
            if (Array.isArray(value) && value.length) {
                return false
            }
            // If the value is an object, check the value property to see if it has a value
            if (value?.hasOwnProperty?.('value') && value.value) {
                return false
            }
            // If the value is of boolean or number type it has a value
            if (typeof value === 'boolean' || typeof value === 'number') {
                return false
            }
            // Otherwise if the item is falsy, the form is missing a value it needs
            return Array.isArray(value) ? true : !value
        })

        this.setState({isFormValid: !isInvalid})

        return true
    }

    get initialState() {
        const {
            cashPercentage,
            courseName,
            description,
            endDate,
            isTeamPortfolios,
            name,
            startDate,
            minRationales,
            minStocksHeld,
            minTrades,
            minBondTrades,
            minEquityTrades,
            minOptionTrades,
            minShortTrades,
            portfolioBenchmarkId,
            portfolioFundingAmount,
            welcomeMessage,
            rankingWeights: {
                diversification,
                engagement,
                return: roi,
                sharpe,
                volatility = 0,
            },
            restrictDayTrading,
        } = this.props.course

        // Find the index of the portfolio benchmark in benchmark options
        const portfolioBenchmarkIndex = benchmarkOptions.findIndex(
            (element) => element.value === portfolioBenchmarkId
        )

        // Find the index of the funding amount in the funding options
        const fundingOptionsIndex = COURSE_PORTFOLIO_FUNDING_AMOUNTS.findIndex(
            (element) => element === portfolioFundingAmount
        )

        const isTrackingCashPercentage = Boolean(cashPercentage)
        const isTrackingHoldings = Boolean(minStocksHeld)
        const isTrackingRationales = Boolean(minRationales)
        const isTrackingTrades = Boolean(minTrades)
        const isTrackingTradesBonds = Boolean(minBondTrades)
        const isTrackingTradesEquities = Boolean(minEquityTrades)
        const isTrackingTradesOptions = Boolean(minOptionTrades)
        const isTrackingTradesShorts = Boolean(minShortTrades)
        const initialMinTrades =
            minTrades ||
            [minBondTrades, minEquityTrades, minOptionTrades].reduce(
                (sum, req) => sum + Number(req),
                0
            )

        return {
            data: {
                [inputNames.COURSE_BENCHMARK]:
                    benchmarkOptions[portfolioBenchmarkIndex] ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_BENCHMARK
                    ],
                [inputNames.COURSE_CODE]:
                    courseName ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_CODE
                    ],
                [inputNames.COURSE_DESCRIPTION]:
                    description ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_DESCRIPTION
                    ],
                [inputNames.COURSE_END_DATE]:
                    [new Date(endDate)] ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_END_DATE
                    ],
                [inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE]:
                    cashPercentage ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS]:
                    minStocksHeld ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES]:
                    minRationales ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES]: initialMinTrades,
                [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS]:
                    minBondTrades ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES]:
                    minEquityTrades ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS]:
                    minOptionTrades ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS
                    ],
                [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS]:
                    minShortTrades ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS
                    ],
                [inputNames.COURSE_INSTITUTION]: {label: '', value: ''},
                [inputNames.COURSE_MESSAGE]:
                    welcomeMessage ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_MESSAGE
                    ],
                [inputNames.COURSE_NAME]:
                    name ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_NAME
                    ],
                [inputNames.COURSE_START_DATE]:
                    [new Date(startDate)] ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_START_DATE
                    ],
                [inputNames.COURSE_STARTING_VALUE]:
                    this.fundingOptions[fundingOptionsIndex] ||
                    CourseSettingsForm.defaultState.data[
                        inputNames.COURSE_STARTING_VALUE
                    ],
                [inputNames.COURSE_ENGAGEMENT_IS_HOLDINGS]: isTrackingHoldings,
                [inputNames.COURSE_ENGAGEMENT_IS_MAX_CASH_PERCENTAGE]: isTrackingCashPercentage,
                [inputNames.COURSE_ENGAGEMENT_IS_RATIONALES]: isTrackingRationales,
                [inputNames.COURSE_ENGAGEMENT_IS_TRADES]: isTrackingTrades,
                [inputNames.COURSE_ENGAGEMENT_IS_TRADES_BONDS]: isTrackingTradesBonds,
                [inputNames.COURSE_ENGAGEMENT_IS_TRADES_EQUITIES]: isTrackingTradesEquities,
                // [inputNames.COURSE_ENGAGEMENT_IS_TRADES_FUTURES]: isTrackingTradesFutures,
                [inputNames.COURSE_ENGAGEMENT_IS_TRADES_OPTIONS]: isTrackingTradesOptions,
                [inputNames.COURSE_ENGAGEMENT_IS_TRADES_SHORTS]: isTrackingTradesShorts,
                [inputNames.COURSE_ENGAGEMENT_IS_TRACKING]:
                    isTrackingCashPercentage ||
                    isTrackingHoldings ||
                    isTrackingRationales ||
                    isTrackingTrades ||
                    isTrackingTradesBonds ||
                    isTrackingTradesEquities ||
                    isTrackingTradesOptions ||
                    isTrackingTradesShorts,
                // isTrackingTradesFutures
                [inputNames.IS_TEAM_PORTFOLIOS]: isTeamPortfolios,
                [inputNames.RANKING_WEIGHT_DIVERSIFICATION]: Number(
                    (diversification * 100).toFixed()
                ),
                [inputNames.RANKING_WEIGHT_ENGAGEMENT]: Number(
                    (engagement * 100).toFixed()
                ),
                [inputNames.RANKING_WEIGHT_RETURN]: Number(
                    (roi * 100).toFixed()
                ),
                [inputNames.RANKING_WEIGHT_SHARPE_RATIO]: Number(
                    (sharpe * 100).toFixed()
                ),
                [inputNames.RANKING_WEIGHT_VOLATILITY]: Number(
                    (volatility * 100).toFixed()
                ),
                [inputNames.RESTRICT_DAY_TRADING]: restrictDayTrading,
                [inputNames.IS_TEAM_PORTFOLIOS]: isTeamPortfolios,
            },
            error: {...CourseSettingsForm.defaultState.error},
            valid: {...CourseSettingsForm.defaultState.valid},
        }
    }

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

    get isEndDateUpdateable() {
        const {course} = this.props
        return course && moment().isSameOrBefore(moment(course.endDate))
    }

    get isStartDateUpdateable() {
        const {course} = this.props
        return course && moment().isBefore(moment(course.startDate))
    }

    getTotalMinTrades({name, value}) {
        const isAnyFlags = this.isAnyTradeFlagEnabled({name, value})
        if (!isAnyFlags) {
            return 0
        }

        return CourseSettingsForm.getFlags('trades').reduce((sum, input) => {
            // if a value was supplied, use it instead of the controlled value
            const inputValue =
                input.key === name
                    ? parseInt(value)
                    : parseInt(this.props.data[input.key])
            const isInputEnabled =
                name === input.flag ? value : this.props.data[input.flag]

            return sum + (isInputEnabled && inputValue ? inputValue : 0)
        }, 0)
    }

    isAnyTradeFlagEnabled({name, value}) {
        return CourseSettingsForm.getFlags('trades').some((input) => {
            // if the flag value is given use it instead of the controlled value
            return name === input.flag ? value : this.props.data[input.flag]
        })
    }

    validate = ({name, value, isRequired}) => {
        const {data, valid} = this.props
        let error = validateInput({name, value, isRequired})

        switch (name) {
            case inputNames.COURSE_INSTITUTION:
                error = validateInput({
                    name,
                    value: value.value,
                    isRequired: true,
                })
                break

            case inputNames.COURSE_END_DATE: {
                const endDate = data[inputNames.COURSE_END_DATE]
                const startDate = data[inputNames.COURSE_START_DATE]

                if (
                    endDate.length &&
                    startDate.length &&
                    moment(endDate[0]).isBefore(startDate[0])
                ) {
                    error = reason.END_DATE_BEFORE_START_ERR
                }

                break
            }

            case inputNames.RANKING_WEIGHT_DIVERSIFICATION:
            case inputNames.RANKING_WEIGHT_ENGAGEMENT:
            case inputNames.RANKING_WEIGHT_RETURN:
            case inputNames.RANKING_WEIGHT_SHARPE_RATIO:
            case inputNames.RANKING_WEIGHT_VOLATILITY: {
                const sum = getSumOfRankingWeights({data})

                if (sum !== 100) {
                    error = 'Sum of Ranking Weights must equal 100.'
                }
            }
        }

        this.props.onValid(valid)
        return error
    }

    onChange = ({name, value}) => {
        const {
            data,
            // updateSchoolSearch,
            onChange,
        } = this.props

        switch (name) {
            // case inputNames.COURSE_ENGAGEMENT_IS_TRADES_FUTURES:
            // case inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_FUTURES:
            case inputNames.COURSE_ENGAGEMENT_IS_TRADES_BONDS:
            case inputNames.COURSE_ENGAGEMENT_IS_TRADES_EQUITIES:
            case inputNames.COURSE_ENGAGEMENT_IS_TRADES_OPTIONS:
            case inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS:
            case inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES:
            case inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS: {
                const newMinTrades = this.getTotalMinTrades({name, value})

                onChange &&
                    onChange({
                        ...data,
                        [name]: value,
                        [inputNames.COURSE_ENGAGEMENT_IS_TRADES]: !!newMinTrades,
                        [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES]: newMinTrades,
                    })
                return
            }

            // case inputNames.COURSE_INSTITUTION:
            //     updateSchoolSearch &&
            //     updateSchoolSearch({query: value.label})
            //     break

            default:
                break
        }

        onChange && onChange({...data, [name]: value})
    }

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

        if (!updateCourse) {
            return
        }

        const {
            [inputNames.COURSE_BENCHMARK]: {value: courseBenchmark},
            [inputNames.COURSE_CODE]: courseCode,
            [inputNames.COURSE_DESCRIPTION]: courseDescription,
            [inputNames.COURSE_END_DATE]: [endDate],
            [inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE]: maxCashPercentage,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS]: minHoldings,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES]: minRationales,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS]: minBondTrades,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES]: minEquityTrades,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS]: minOptionsTrades,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS]: minShortTrades,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES]: minTotalTrades,
            [inputNames.COURSE_MESSAGE]: courseMessage,
            [inputNames.COURSE_NAME]: courseName,
            [inputNames.COURSE_START_DATE]: [startDate],
            [inputNames.IS_TEAM_PORTFOLIOS]: isTeamPortfolios,
            [inputNames.RANKING_WEIGHT_DIVERSIFICATION]: diversification,
            [inputNames.RANKING_WEIGHT_ENGAGEMENT]: engagement,
            [inputNames.RANKING_WEIGHT_RETURN]: roi,
            [inputNames.RANKING_WEIGHT_SHARPE_RATIO]: sharpe,
            [inputNames.RANKING_WEIGHT_VOLATILITY]: volatility,
            [inputNames.RESTRICT_DAY_TRADING]: restrictDayTrading,
        } = data

        const payload = sparsifyObj({
            [inputNames.COURSE_BENCHMARK]: courseBenchmark,
            [inputNames.COURSE_CODE]: courseCode,
            [inputNames.COURSE_DESCRIPTION]: courseDescription,
            [inputNames.COURSE_END_DATE]: moment(endDate).format(),
            [inputNames.COURSE_ENGAGEMENT_MAX_CASH_PERCENTAGE]: maxCashPercentage
                ? Number(maxCashPercentage)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_HOLDINGS]: minHoldings
                ? Number(minHoldings)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_RATIONALES]: minRationales
                ? Number(minRationales)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_BONDS]: minBondTrades
                ? Number(minBondTrades)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_EQUITIES]: minEquityTrades
                ? Number(minEquityTrades)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_OPTIONS]: minOptionsTrades
                ? Number(minOptionsTrades)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_SHORTS]: minShortTrades
                ? Number(minShortTrades)
                : null,
            [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES]: minTotalTrades
                ? Number(minTotalTrades)
                : null,
            [inputNames.COURSE_MESSAGE]: courseMessage,
            [inputNames.COURSE_NAME]: courseName,
            [inputNames.COURSE_START_DATE]: moment(startDate).format(),
            // [inputNames.COURSE_ENGAGEMENT_TOTAL_TRADES_FUTURES]: minFutureTrades,
            courseId: course.id,
            [inputNames.IS_TEAM_PORTFOLIOS]: isTeamPortfolios,
            rankingWeights: {
                diversification: diversification / 100,
                engagement: engagement / 100,
                return: roi / 100,
                sharpe: sharpe / 100,
                volatility: volatility / 100,
            },
            [inputNames.RESTRICT_DAY_TRADING]: restrictDayTrading,
        })

        // Remove start date from PATCH payload if current date is after start date
        if (!this.isStartDateUpdateable) {
            delete payload[inputNames.COURSE_START_DATE]
        }

        if (!this.isEndDateUpdateable) {
            delete payload[inputNames.COURSE_END_DATE]
        }

        // Remove values if they aren't enabled
        CourseSettingsForm.getFlags().forEach((input) => {
            if (
                !data[inputNames.COURSE_ENGAGEMENT_IS_TRACKING] ||
                !data[input.flag]
            ) {
                payload[input.key] = null
            }
        })

        updateCourse(payload)
            .then(() => onSubmit && onSubmit(payload))
            .catch((err) => {
                if (!err.inlineErrors || !err.inlineErrors.length || !onError) {
                    return
                }

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

                onError && onError(error)
            })
    }

    submitButton = ({disabled, submit}) => {
        const submitButtonClassNames = bem.classNames(
            'c-course-creation__button'
        )

        return (
            <Button
                className={submitButtonClassNames}
                disabled={disabled}
                variant="primary"
                text="Update"
                onClick={submit}
            />
        )
    }

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

        const {isFormValid} = this.state

        return (
            <Form
                data={data}
                error={error}
                name={CourseSettingsForm.formName}
                ref={this.form}
                submitOnEnter={false}
                validate={this.validate}
                validateOnUpdate
                onChange={this.onChange}
                onError={onError}
                onUpdate={this.onChange}
                onSubmit={this.updateCourse}
            >
                <ChallengeCustomization
                    data={data}
                    isUpdate={true}
                    user={user}
                />

                <Form.SubmitTrigger
                    disabled={!isFormValid}
                    render={this.submitButton}
                />
            </Form>
        )
    }
}

CourseSettingsForm.defaultProps = {
    data: {...CourseSettingsForm.defaultState.data},
    error: {...CourseSettingsForm.defaultState.error},
    valid: {...CourseSettingsForm.defaultState.valid},
}

CourseSettingsForm.propTypes = {
    course: PropTypes.object,
    data: PropTypes.object,
    error: PropTypes.object,
    schoolSuggestions: PropTypes.object,
    updateCourse: PropTypes.func,
    updateSchoolSearch: PropTypes.func,
    user: PropTypes.shape({
        schoolId: PropTypes.string,
    }),
    valid: PropTypes.object,
    onChange: PropTypes.func,
    onError: PropTypes.func,
    onSubmit: PropTypes.func,
    onValid: PropTypes.func,
}

export default CourseSettingsForm
