// login.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 { useHistory } from 'react-router'
import { faIdCard } from '@fortawesome/free-solid-svg-icons'

import { handleApiError } from '../../api/errors'
import { authenticate } from '../../actions/authentication'
import { showNotification } from '../../actions/notifications'
import { getChecked, getAuthenticated } from '../../selectors/authentication'
import { getFieldValue } from '../../selectors/forms'
import { getIsFetching } from '../../selectors/requests'
import { initForm, initField, setFieldNotification } from '../../actions/forms'

import Title from '../../components/title'
import Section from '../../components/section'
import TextField from '../../components/controls/text-field'
import PasswordField from '../../components/controls/password-field'
import PrimaryButton from '../../components/controls/primary-button'

import { AppState, RequestKey, NotificationType } from '../../types'

const Login: FC = () => {
    const checked = useSelector(getChecked)
    const authenticated = useSelector(getAuthenticated)
    const name = useSelector<AppState, string>(state => getFieldValue(state, 'name', ''))
    const password = useSelector<AppState, string>(state => getFieldValue(state, 'password', ''))
    const authenticating = useSelector<AppState, boolean>(state => getIsFetching(state, RequestKey.Authenticate))

    const dispatch = useDispatch()
    const history = useHistory()

    useEffect(() => {
        if (checked && authenticated) history.push('/self')
    }, [checked, authenticated])
    
    useEffect(() => {
        dispatch(initForm())
        dispatch(initField('name', '', 'id'))
        dispatch(initField('password', ''))
    }, [])

    const handleAuthenticate = async () => {
        let invalid = false

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

        if (!password) {
            dispatch(setFieldNotification('password', NotificationType.Error, 'This is required'))
            invalid = true
        }

        if (invalid) return

        try {
            const id = await dispatch(authenticate(name, password))
            dispatch(showNotification(NotificationType.Welcome, `Welcome back ${id}!`))
            history.push('/')
        } catch (err) {
            handleApiError(err, dispatch, history)
        }
    }
    
    return (
        <div>
            <Section>
                <Title>Log In to Flexor</Title>

                <TextField icon={faIdCard} name="name" label="Username" placeholder="Your Username/ID" />
                <PasswordField placeholder="Your password" showStrength={false} />

                <PrimaryButton text="Log In" onClick={() => handleAuthenticate()} loading={authenticating} />
            </Section>
        </div>
    )
}

export default Login
