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'


// /* Feathers Client */
// const io = require('socket.io-client');
// const feathers = require('@feathersjs/feathers');
// const socketio = require('@feathersjs/socketio-client');

// const socket = io('http://api.chroma.vision');
// const client = feathers();

// client.configure(socketio(socket));




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

    // const rootStore = useStores()
    
    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)
                
                // 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 }))
            }
        })
    }

    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"
                    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>

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

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

export default LoginForm
