import React, { FC } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons'

import { setFieldNotification } from '../actions/forms'
import { showNotification } from '../actions/notifications'
import { setStep } from '../actions/registration'
import { getForm } from '../selectors/forms'

import { valueFromForm } from '../utils'
import { MAX_ID_LENGTH } from '../constants'
import { AppThunkDispatch, NotificationType } from '../types'

import CreateGroupForm from './create-group-form'
import HorizontalRule from '../components/horizontal-rule'
import PrimaryButton from '../components/controls/primary-button'
import SecondaryButton from '../components/controls/secondary-button'

interface Props {
    register: () => void
}

const CreateGroupStep: FC<Props> = ({ register }) => {
    const form = useSelector(getForm)
    const dispatch = useDispatch<AppThunkDispatch>()

    const next = () => {
        let invalid = false

        const name = valueFromForm<string>(form, 'group-name')
        const agree = valueFromForm<boolean>(form, 'group-agree')

        if (!name || name === '') {
            dispatch(setFieldNotification('group-name', NotificationType.Error, 'This is required'))
            invalid = true
        }

        if (name && name.length > MAX_ID_LENGTH) {
            dispatch(setFieldNotification('group-name', NotificationType.Error, `This must be less than ${MAX_ID_LENGTH} characters`))
            invalid = true
        }

        if (!agree) {
            dispatch(setFieldNotification('group-agree', NotificationType.Error, 'You must agree to the terms and conditions to continue'))
            dispatch(showNotification(NotificationType.Error, 'You must agree to the terms and conditions to continue.'))
            invalid = true
        }

        if (invalid) return
        register()
    }

    return (
        <div>
            <CreateGroupForm />
            <HorizontalRule />

            <nav className="level">
                <div>
                    <SecondaryButton text="Your Account" icon={faArrowLeft} onClick={() => dispatch(setStep(0))} />
                </div>

                <div>
                    <PrimaryButton text="Finish" onClick={() => next()} />
                </div>
            </nav>
        </div>
    )
}

export default CreateGroupStep
