// register-group.tsx
// Copyright (C) 2020  Dwayne Harris

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

import React, { FC, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useParams, useHistory } from 'react-router'
import { faUserPlus } from '@fortawesome/free-solid-svg-icons'

import { handleApiError } from '../../api/errors'
import { fetchGroup } from '../../actions/groups'
import { initField } from '../../actions/forms'
import { showNotification } from '../../actions/notifications'
import { register } from '../../actions/registration'
import { getEntity } from '../../selectors/entities'
import { getForm } from '../../selectors/forms'

import { setTitle, valueFromForm, getDefaultThemeName } from '../../utils'
import { useDeepCompareEffect } from '../../hooks'

import { AppState, AppThunkDispatch, Group, EntityType, NotificationType } from '../../types'

import Title from '../../components/title'
import Subtitle from '../../components/subtitle'
import Section from '../../components/section'
import HorizontalRule from '../../components/horizontal-rule'
import PrimaryButton from '../../components/controls/primary-button'
import Loading from '../../components/pages/loading'
import CreateUserForm from '../../components/create-user-form'

interface Params {
    id: string
}

const RegisterGroup: FC = () => {
    const { id } = useParams<Params>()
    const group = useSelector<AppState, Group | undefined>(state => getEntity(state, EntityType.Group, id))
    const form = useSelector(getForm)
    const dispatch = useDispatch<AppThunkDispatch>()
    const history = useHistory()

    useEffect(() => {
        try {
            dispatch(fetchGroup(id))
        } catch (err) {
            handleApiError(err, dispatch, history)
        }

        dispatch(initField('user-id', '', 'id'))
        dispatch(initField('user-name', '', 'name'))
        dispatch(initField('user-email', '', 'email'))
        dispatch(initField('password', ''))
        dispatch(initField('user-theme', getDefaultThemeName(), 'theme'))
        dispatch(initField('user-image', '', 'imageUrl'))
        dispatch(initField('user-cover-image', '', 'coverImageUrl'))
        dispatch(initField('user-agree', false))

        setTitle('Register')
    }, [])

    useDeepCompareEffect(() => {
        if (group) setTitle(`Register with ${group.name}`)
    }, [group])

    const handleRegister = async () => {
        if (!valueFromForm<boolean>(form, 'user-agree', false)) {
            dispatch(showNotification(NotificationType.Error, 'You must agree to the 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', 'public'),
                group: id,
                theme: valueFromForm<string>(form, 'user-theme', getDefaultThemeName()),
            }))

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

    if (!group) return <Loading />

    return (
        <div>
            <Section>
                <Title>Register</Title>
                <Subtitle>{group.name}</Subtitle>
                <HorizontalRule />

                <CreateUserForm />
                <br />

                <PrimaryButton text="Create Your Account" icon={faUserPlus} onClick={() => handleRegister()} />
            </Section>
        </div>
    )
}

export default RegisterGroup
