import React from 'react'

import chromajs from '@chromaplatform/chromajs'

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

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



const RegistrationForm = (props) => {
    const [email, setEmail] = React.useState()
    const [password, setPassword] = React.useState()
    const [passwordVerification, setPasswordVerification] = React.useState()
    const [username, setUsername] = React.useState()
    const [status, setStatus] = React.useState({status: "ready", errors: ['']})
    
    const handleRegister = (e) => {
        setStatus({status: "pending", errors: ['']})

        let authRequest = {
            'email': email,
            'password': password,
            'username': username,
            'strategy': 'local'
        }

        // Verify passwords match
        if(password !== passwordVerification) {
            setStatus({status: "error", errors: ['Passwords do not match']})
        } else {
            /* Make Authentication Socket Reqeust */
            chromajs.socket.emit('create', 'users', authRequest, (error, authResult) => {
                if(error){
                    console.log(error)
                    if(error.errors){
                        setStatus({status: "error", errors: error.errors})
                        global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: {status: "error", errors: error.errors} }))
                    } else {
                        setStatus({status: "error", errors: [error.message]})
                        global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: {status: "error", errors: [error.message]} }))
                    }
                } else {
                    console.log(authResult)
                    let callbackResult = {}

                    if(authResult.accessToken){
                        callbackResult.authenticated = true
                        callbackResult.email = authResult.email
                        callbackResult.username = authResult.username
                        callbackResult.id = authResult._id
                        callbackResult.token = authResult.accessToken
                    }

                    /* Broadcast success event */
                    global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: callbackResult }))
                }
            })
        }

        
    }

    return (
        <Pane className="registration-form">
            {/* Feedback */}
            {status.status !== "error" ? "" : <Alert
                appearance="card"
                intent="danger"
                title={status.errors[0]}
            />}

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

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

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

            {/* Password Verify */}
            <Pane>
                <TextInput
                    name="text-input-password-verify"
                    placeholder="Password Verification"
                    type="password"
                    onChange={event => setPasswordVerification(event.target.value)}
                />
            </Pane>

            {/* Submit */}
            <Pane float="right">
                <Button appearance="primary" disabled={status.status === "pending" ? true : false} onClick={() => handleRegister()}>Register</Button>
            </Pane>

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

export default RegistrationForm
