import React from 'react'

import chromajs from '@chromaplatform/chromajs'

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

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

/* Utilities */
const _ = require('lodash')


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: ['']})

    let API_ENDPOINT = props.chromaEndpoint || 'https://api.chroma.vision'

    const handleEnterClick = (event) => {
        if(event.key === 'Enter'){
            console.log('Clicked / Enter')
            if(status.status === "ready"){
                console.log('Clicked / Enter Ready')
                event.target.blur()
                handleRegister()
            }
        }
    }
    
    const handleRegister = (e) => {
        setStatus({status: "pending", errors: ['']})

        // Allow override of chroma_config.origin
        let userOrigin
        if (typeof window !== "undefined") {
            userOrigin = _.get(window, "localStorage.chroma_config.origin") || {
                'publisherId': "5e896473c27845723a02a5a6",
                'appId': "5f05fe6f1811bb39eae1171c"
            }    
        }
        

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

        // Verify passwords match
        if(password !== passwordVerification) {
            setStatus({status: "error", errors: ['Passwords do not match']})
        } else {
            /* Refactor to REST */
            // NEW REST WAY
            fetch(API_ENDPOINT + `/users/`, {
                method: 'POST',
                body: JSON.stringify(authRequest),
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            })
            .then(res => res.json())
            .then(
                (authResult) => {
                    console.log("request", authResult)

                    // Check for errors
                    const error = _.get(authResult, "name")

                    if(error === "GeneralError"){
                        const message = _.get(authResult, "message")
                        console.log("message", message)

                        switch(message){
                            default:
                                setStatus({status: "error", errors: [message]})
                                break;
                            case "USERNAME_IN_USE":
                                setStatus({status: "error", errors: ['Username not available']})
                                break
                            case "EMAIL_IN_USE":
                                setStatus({status: "error", errors: ['Email already in use']})
                                break
                        }
                    } else {
                        // 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"]} }))
                            global.dispatchEvent(new CustomEvent('/user/registered', { bubbles: true, detail: {status: "verify"} }))
                        }

                        setStatus({status: "ready", errors: ['']})
                    }
            })
            
            /* LEGACY - 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 {
            //         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 }))
            //         } else {
            //             global.dispatchEvent(new CustomEvent('/user/registered', { bubbles: true, detail: {status: "verify"} }))
            //             // reset this form and switch back to login
            //         }

            //     }
            // })
        }

        
    }

    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"
                    onKeyPress={handleEnterClick}
                    onChange={event => setPasswordVerification(event.target.value)}
                />
            </Pane>

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

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

export default RegistrationForm
