// edit-app.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, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useParams, useHistory } from 'react-router-dom'
import { faIdCard, faCheckCircle, faKey, faShieldAlt, faLink, faAddressBook, faCodeBranch } from '@fortawesome/free-solid-svg-icons'

import { handleApiError } from '../../api/errors'
import { fetchApp, updateApp } from '../../actions/apps'
import { initForm, initField, setFieldNotification } from '../../actions/forms'
import { showNotification } from '../../actions/notifications'
import { getAuthenticatedUserId } from '../../selectors/authentication'
import { getEntity } from '../../selectors/entities'
import { getForm } from '../../selectors/forms'
import { getIsFetching } from '../../selectors/requests'

import { useAuthenticationCheck, useDeepCompareEffect, useTheme } from '../../hooks'
import { setTitle, valueFromForm } from '../../utils'
import { AppState, AppThunkDispatch, EntityType, App, NotificationType, RequestKey } from '../../types'

import Title from '../../components/title'
import Section from '../../components/section'
import HorizontalRule from '../../components/horizontal-rule'
import Loading from '../../components/pages/loading'
import TextField from '../../components/controls/text-field'
import TextareaField from '../../components/controls/textarea-field'
import ImageField from '../../components/controls/image-field'
import CoverImageField from '../../components/controls/cover-image-field'
import IconImageField from '../../components/controls/icon-image-field'
import StaticField from '../../components/controls/static-field'
import PrimaryButton from '../../components/controls/primary-button'

interface Params {
    id: string
}

const EditApp: FC = () => {
    useAuthenticationCheck()

    const theme = useTheme()
    const { id } = useParams<Params>()
    const fetching = useSelector<AppState, boolean>(state => getIsFetching(state, RequestKey.UpdateApp))
    const app = useSelector<AppState, App | undefined>(state => getEntity<App>(state, EntityType.App, id))
    const form = useSelector(getForm)
    const selfId = useSelector(getAuthenticatedUserId)
    const dispatch = useDispatch<AppThunkDispatch>()
    const history = useHistory()
    const [showPrivateKey, setShowPrivateKey] = useState(false)

    useEffect(() => {
        try {
            dispatch(fetchApp(id))
        } catch (err) {
            handleApiError(err, dispatch, history)
        }
    }, [])

    useDeepCompareEffect(() => {
        if (app) {
            if (app.user.id !== selfId) {
                history.push(`/a/${id}`)
            }

            setTitle(app.name)

            dispatch(initForm())
            dispatch(initField('name', app.name))
            dispatch(initField('about', app.about ?? ''))
            dispatch(initField('websiteUrl', app.websiteUrl ?? ''))
            dispatch(initField('companyName', app.companyName ?? ''))
            dispatch(initField('version', ''))
            dispatch(initField('composerUrl', app.composerUrl ?? ''))
            dispatch(initField('rendererUrl', app.rendererUrl ?? ''))
            dispatch(initField('image', app.imageUrl ?? ''))
            dispatch(initField('coverImage', app.coverImageUrl ?? ''))
            dispatch(initField('iconImage', app.iconImageUrl ?? ''))
        }
    }, [app])

    if (!app) return <Loading />

    const handleUpdate = async () => {
        const name = valueFromForm<string>(form, 'name')
        const about = valueFromForm<string>(form, 'about')
        const websiteUrl = valueFromForm<string>(form, 'websiteUrl')
        const companyName = valueFromForm<string>(form, 'companyName')
        const version = valueFromForm<string>(form, 'version')
        const composerUrl = valueFromForm<string>(form, 'composerUrl')
        const rendererUrl = valueFromForm<string>(form, 'rendererUrl')
        const imageUrl = valueFromForm<string>(form, 'image')
        const coverImageUrl = valueFromForm<string>(form, 'coverImage')
        const iconImageUrl = valueFromForm<string>(form, 'iconImage')

        if (!name) {
            dispatch(showNotification(NotificationType.Error, 'Name is required'))
            dispatch(setFieldNotification('name', NotificationType.Error, 'This is required'))
            return
        }

        if (!version) {
            dispatch(showNotification(NotificationType.Error, 'Version is required'))
            dispatch(setFieldNotification('version', NotificationType.Error, 'This is required'))
            return
        }

        try {
            await dispatch(updateApp(id, {
                name,
                about,
                websiteUrl,
                companyName,
                version,
                composerUrl,
                rendererUrl,
                imageUrl,
                coverImageUrl,
                iconImageUrl,
            }))

            dispatch(showNotification(NotificationType.Success, 'Updated!'))

            setTimeout(() => {
                history.push(`/a/${app.id}`)
            }, 1000)
        } catch (err) {
            handleApiError(err, dispatch, history)
        }
    }

    const privateKeyDisplay = showPrivateKey ? app.privateKey : '********'

    return (
        <div>
            <Section>
                <Title>{app.name}</Title>
                <HorizontalRule />

                <div>
                    <StaticField label="Public Key" icon={faKey} value={app.publicKey} />
                    <StaticField label="Private Key" icon={faShieldAlt} value={privateKeyDisplay} />
                    <a style={{ display: 'block', fontSize: '0.75rem', color: theme.secondary, marginTop: '-2rem' }} onClick={() => setShowPrivateKey(!showPrivateKey)}>{showPrivateKey ? 'Hide' : 'Show'}</a>

                    <HorizontalRule />

                    <StaticField label="ID" icon={faIdCard} />
                    <TextField name="name" label="Name" icon={faIdCard} placeholder="App Name" />
                    <TextareaField name="about" label="About" placeholder="Description of this app" />
                    <TextField name="websiteUrl" label="Website" icon={faLink} placeholder="Website URL (optional)" />
                    <TextField name="companyName" label="Company" icon={faAddressBook} placeholder="Your company or organization (optional)" />
                    <TextField name="version" label="Version" icon={faCodeBranch} placeholder="Current Version of the app (ex: 0.0.1beta5)" help={`Last Version: ${app.version}`} />
                    <HorizontalRule />

                    <ImageField name="image" />
                    <CoverImageField name="coverImage" />
                    <IconImageField name="iconImage" />
                    <HorizontalRule />

                    <TextField name="composerUrl" label="Composer URL" icon={faLink} placeholder="URL for the composer web page" />
                    <TextField name="rendererUrl" label="Renderer URL" icon={faLink} placeholder="URL for the renderer template" />
                    <br /><br />

                    <PrimaryButton text="Save" icon={faCheckCircle} loading={fetching} onClick={() => handleUpdate()} />
                </div>
            </Section>
        </div>
    )
}

export default EditApp
