import React, { FC, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from 'react-router'

import { handleApiError } from '../../api/errors'
import { getForm } from '../../selectors/forms'
import { getStep } from '../../selectors/registration'
import { initForm, initField } from '../../actions/forms'
import { showNotification } from '../../actions/notifications'
import { createGroup, register } from '../../actions/registration'
import { setTitle, valueFromForm, getDefaultThemeName } from '../../utils'
import { AppThunkDispatch, NotificationType } from '../../types'

import Title from '../../components/title'
import Section from '../../components/section'
import HorizontalRule from '../../components/horizontal-rule'
import CreateGroupStep from '../../components/create-group-step'
import CreateUserStep from '../../components/create-user-step'

const Register: FC = () => {
    const stepIndex = useSelector(getStep)
    const form = useSelector(getForm)

    const dispatch = useDispatch<AppThunkDispatch>()
    const history = useHistory()

    const handleRegister = async () => {
        const groupAgree = valueFromForm<boolean>(form, 'group-agree', false)
        const userAgree = valueFromForm<boolean>(form, 'user-agree', false)

        if (!groupAgree || !userAgree) {
            dispatch(showNotification(NotificationType.Error, 'You must agree to both Community and User terms and conditions.'))
            return
        }

        try {
            await dispatch(register({
                id: valueFromForm<string>(form, 'user-id', ''),
                email: valueFromForm<string>(form, 'user-email', ''),
                password: valueFromForm<string>(form, 'password', ''),
                name: valueFromForm<string>(form, 'user-name', ''),
                imageUrl: valueFromForm<string>(form, 'user-image', ''),
                coverImageUrl: valueFromForm<string>(form, 'user-cover-image', ''),
                requiresApproval: valueFromForm<boolean>(form, 'user-requires-approval', false),
                privacy: valueFromForm<string>(form, 'user-privacy', 'open'),
                theme: valueFromForm<string>(form, 'user-theme', getDefaultThemeName()),
            }))

            await dispatch(createGroup({
                name: valueFromForm<string>(form, 'group-name', ''),
                registration: valueFromForm<string>(form, 'group-registration', ''),
                imageUrl: valueFromForm<string>(form, 'group-image', ''),
                coverImageUrl: valueFromForm<string>(form, 'group-cover-image', ''),
                iconImageUrl: valueFromForm<string>(form, 'group-icon-image', ''),
                theme: valueFromForm<string>(form, 'group-theme', getDefaultThemeName()),
            }))

            dispatch(showNotification(NotificationType.Welcome, `Welcome to Flexor!`))
    
            location.href = '/self'
        } catch (err) {
            handleApiError(err, dispatch, history)
        }
    }

    const title = () => {
        switch (stepIndex) {
            case 0: return 'Create Your Account'
            default: return 'Create a Community'
        }
    }

    const component = () => {
        switch (stepIndex) {
            case 0: return <CreateUserStep />
            default: return <CreateGroupStep register={() => handleRegister()} />
        }
    }

    useEffect(() => {
        dispatch(initForm())
        dispatch(initField('group-name', '', 'name'))
        dispatch(initField('group-registration', 'open', 'registration'))
        dispatch(initField('group-image', '', 'imageUrl'))
        dispatch(initField('group-cover-image', '', 'coverImageUrl'))
        dispatch(initField('group-icon-image', '', 'iconImageUrl'))
        dispatch(initField('group-theme', getDefaultThemeName(), 'theme'))
        dispatch(initField('group-agree', false))
        dispatch(initField('user-id', '', 'id'))
        dispatch(initField('user-name', '', 'name'))
        dispatch(initField('user-email', '', 'email'))
        dispatch(initField('password', ''))
        dispatch(initField('user-image', '', 'imageUrl'))
        dispatch(initField('user-cover-image', '', 'coverImageUrl'))
        dispatch(initField('user-requires-approval', false, 'requiresApproval'))
        dispatch(initField('user-privacy', 'public', 'privacy'))
        dispatch(initField('user-theme', getDefaultThemeName(), 'theme'))
        dispatch(initField('user-agree', false))
    }, [])

    useEffect(() => {
        setTitle(title())
    }, [stepIndex])

    return (
        <div>
            <Section>
                <Title>{title()}</Title>
                <HorizontalRule />

                {component()}
            </Section>
        </div>
    )
}

export default Register
