import React from 'react'

import chromajs from '@chromaplatform/chromajs'

/* Media */
import './auth-login.css'

/* Views & Components */

/* Models */
// import { useStores } from '../../../models/RootStoreContext'

/* UI Framework */
import { Alert, Button, Pane, TextInput } from 'evergreen-ui'


const LoginForm = (props) => {
    const [email, setEmail] = React.useState()
    const [password, setPassword] = React.useState()
    const [status, setStatus] = React.useState({status: "ready"})

    // const rootStore = useStores()

    const handleEnterClick = (event) => {
        if(event.key === 'Enter'){
            if(status.status === "ready"){
                event.target.blur()
                handleAuth()
            }
        }
    }
    
    const handleAuth = (e) => {
        setStatus({status: "pending"})

        let authRequest

        // Check if username or email
        if(email && email.includes("@")) {
            authRequest = {
                "email": email,
                "password": password,
                "strategy": "local"
            }
        } else {
            authRequest = {
                "username": email,
                "password": password,
                "strategy": "username"
            }
        }

        /* Make Authentication Socket Reqeust */
        chromajs.socket.emit('create', 'authentication', authRequest, (error, authResult) => {
            if(error){
                console.log(error)
                setStatus({status: "error", errors: error.message})
                
                global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: {status: "error", errors: error.message} }))
            } else {
                console.log(authResult)

                // Check if auth aws successful
                if(authResult.accessToken){
                        // Configure success callback results
                    let callbackResult = {}
                    callbackResult.authenticated = true
                    callbackResult.email = authResult.user.email
                    callbackResult.username = authResult.user.username
                    callbackResult.id = authResult.user._id
                    callbackResult.token = authResult.accessToken

                    /* BROADCAST LOGIN SUCCESS EVENT HERE */
                    global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: callbackResult }))
                } else {
                    global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: {status: "error", errors: ["INVALID_AUTH"]} }))
                }
                
               
            }
        })
    }

    return (
        <Pane className="login-form">
            {/* Feedback */}
            {status.status !== "error" ? "" : <Alert
                appearance="card"
                intent="danger"
                title="Invalid credentials"
            />}

            {/* Email */}
            <Pane>
                <TextInput
                    name="text-input-email"
                    placeholder="Email or Username"
                    onChange={event => setEmail(event.target.value)}
                />
            </Pane>

            {/* Password */}
            <Pane>
                <TextInput
                    name="text-input-password"
                    placeholder="Password"
                    type="password"
                    onKeyPress={handleEnterClick}
                    onChange={event => setPassword(event.target.value)}
                />
            </Pane>

            {/* Submit */}
            <Pane>
                <Button className="button" appearance="primary" disabled={status.status === "pending" ? true : false} onClick={() => handleAuth()}>Login</Button>
            </Pane>

            <Pane className="clear" />
        </Pane>
    );
}

export default LoginForm
