import React, { FC } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { faDoorOpen, faCheckCircle, faIdCard, faEnvelope, faUserShield, faUserCircle } from '@fortawesome/free-solid-svg-icons'

import { unauthenticate, updateSelf } from '../../actions/authentication'
import { initForm, initField } from '../../actions/forms'
import { getAuthenticatedUser } from '../../selectors/authentication'
import { getForm } from '../../selectors/forms'

import { handleApiError } from '../../api/errors'
import { PRIVACY_OPTIONS } from '../../constants'
import { useAuthenticationCheck, useDeepCompareEffect } from '../../hooks'
import { setTitle, valueFromForm } from '../../utils'

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 SecondaryButton from '../../components/controls/secondary-button'
import Loading from '../../components/pages/loading'
import TextField from '../../components/controls/text-field'
import TextareaField from '../../components/controls/textarea-field'
import SelectField from '../../components/controls/select-field'
import CheckboxField from '../../components/controls/checkbox-field'
import ImageField from '../../components/controls/image-field'
import CoverImageField from '../../components/controls/cover-image-field'
import ThemeField from '../../components/controls/theme-field'
import StaticField from '../../components/controls/static-field'

const Self: FC = () => {
    const dispatch = useDispatch()
    const history = useHistory()

    const user = useSelector(getAuthenticatedUser)
    const form = useSelector(getForm)

    useAuthenticationCheck()

    const handleLogout = () => {
        localStorage.clear()
        dispatch(unauthenticate())
        window.location.href = '/'
    }

    const handleUpdate = () => {
        if (!user) return
        const settings = user.settings ?? {}
        const name = valueFromForm<string>(form, 'name', '')
        const about = valueFromForm<string>(form, 'about', '')
        const requiresApproval = valueFromForm<boolean>(form, 'requiresApproval', true)
        const privacy = valueFromForm<string>(form, 'privacy', 'public')
        const imageUrl = valueFromForm<string>(form, 'image', '')
        const coverImageUrl = valueFromForm<string>(form, 'coverImage', '')
        const theme = valueFromForm<string>(form, 'theme', '')
        const allowThemeChange = valueFromForm<boolean>(form, 'allowThemeChange', true)

        try {
            dispatch(updateSelf({
                name,
                about,
                requiresApproval,
                privacy,
                imageUrl,
                coverImageUrl,
                theme,
                settings: {
                    ...settings,
                    allowThemeChange,
                }
            }))
        } catch (err) {
            handleApiError(err, dispatch, history)
        }
    }

    useDeepCompareEffect(() => {
        if (user) {
            setTitle(`${user.name} @${user.id}`)
            
            dispatch(initForm())
            dispatch(initField('name', user.name))
            dispatch(initField('about', user.about ?? ''))
            dispatch(initField('requiresApproval', user.requiresApproval))
            dispatch(initField('privacy', user.privacy))
            dispatch(initField('image', user.imageUrl ?? ''))
            dispatch(initField('coverImage', user.coverImageUrl ?? ''))
            dispatch(initField('theme', user.theme))
            dispatch(initField('allowThemeChange', user.settings.allowThemeChange))
        }
    }, [user])

    if (!user) return <Loading />

    return (
        <div>
            <Section>
                <Title>{user.name ?? user.id}</Title>
                <Subtitle>@{user.id}</Subtitle>

                <HorizontalRule />

                <PrimaryButton text="Your Page" icon={faUserCircle} onClick={() => history.push(`/u/${user.id}`)} />

                <StaticField label="ID" icon={faIdCard} value={user.id} />
                <StaticField label="ID" icon={faEnvelope} value={user.email} />
                <TextField name="name" label="Name" placeholder="Your Display Name" />
                <TextareaField name="about" label="About" placeholder="Your Bio" />
                <ThemeField name="theme" label="Color" />
                <SelectField name="privacy" label="Privacy" options={PRIVACY_OPTIONS} icon={faUserShield} />
                <ImageField name="image" label="Avatar" />
                <CoverImageField name="coverImage" />
                <CheckboxField name="requiresApproval">
                    Approve each Subscription request from other users.
                </CheckboxField>
                <br />

                <CheckboxField name="allowThemeChange">
                    Allow theme changes on User and Community pages.
                </CheckboxField>
                
                <HorizontalRule />

                <nav className="level">
                    <div>
                        <PrimaryButton text="Save" icon={faCheckCircle} onClick={() => handleUpdate()} />
                    </div>

                    <div>
                        <SecondaryButton text="Log Out" icon={faDoorOpen} onClick={() => handleLogout()} />
                    </div>
                </nav>
            </Section>
        </div>
    )
}

export default Self
