import React from 'react'

import chromajs from '@chromaplatform/chromajs'

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

/* Views & Components */
import LoginForm from './auth-login'
import RegistrationForm from './auth-register'
import SocialForm from './auth-social'
import ForgotForm from './auth-forgot'

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

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

const Auth = (props) => {
    /* States */
    const [authUIState, setAuthUIState] = React.useState("login")

    /* Capture incoming token & info */
    const url_params = new URLSearchParams(window.location.search)
    
    /* If token exists, auth & redirect */
    if(url_params.has('token')){
        // Send token to /user/authenticated event path
        const incoming_token = url_params.get('token')

        let id = ""
        if(url_params.has('id')){
            id = url_params.get('id')
        }

        setTimeout(() => {
            // Electron event
            global.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: { token: incoming_token, id: id } }))

            // Needed redundancy (for now) to enable web & electron
            window.dispatchEvent(new CustomEvent('/user/authenticated', { bubbles: true, detail: { token: incoming_token, id: id } }))
            console.log("DISPATCHED EVENT token:", incoming_token)
        }, 500)
        
        
        // Remove params
        const url = new URL(window.location.href)
        const params = new URLSearchParams(url.search.slice(1))
        params.delete('token')
        params.delete('source')

        window.history.replaceState(
            {},
            '',
            `${window.location.pathname}`,
        )

    }



    const continueAsGuest = (e) => {
        // Check if user_hash exists (will not work on electron YET)
        let local_user_hash = window.localStorage.getItem('chroma_user_hash')

        if(local_user_hash === null) {
            // no local guest user

            // generate user_hash
            const crypto = require('crypto')
            var current_date = (new Date()).valueOf().toString();
            var random = Math.random().toString();
            local_user_hash = crypto.createHash('sha1').update(current_date + random).digest('hex');
        }

        /* Make Authentication Socket Reqeust */
        const guestAuthRequest = {
            "user_hash": local_user_hash
        }
        chromajs.socket.emit('create', 'users/guest', guestAuthRequest, (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 {

                // Check if auth aws successful
                if(authResult.accessToken){
                        // Configure success callback results
                    let callbackResult = {}
                    callbackResult.authenticated = true
                    callbackResult.email = authResult.email
                    callbackResult.username = authResult.username
                    callbackResult.id = authResult.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"]} }))
                }

                // Store local user hash
                window.localStorage.setItem('chroma_user_hash', local_user_hash)
            }
        })
    }

    return (
        <Pane className={`chroma-auth ${authUIState}`}>
            <Pane className={`form social`} flex={5} padding={24}>
                <SocialForm user_hash={props.user_hash} source={props.source}  />
            </Pane>

            <Pane className={`form divider`}>
                <Pane className="left" />
                <Text className="text">OR</Text>
                <Pane className="right" />
            </Pane>

            <Pane className="clear" />

            <Pane className={`form login`} flex={5}>
                {/* <h3 className="title">Login</h3> */}
                {/* <LoginForm callback={props.config.login_callback} /> */}
                <LoginForm />
            </Pane>

            <Pane className={`form register`} flex={5}>
                {/* <h3 className="title">Register</h3> */}
                {/* <RegistrationForm callback={props.config.registration_callback} /> */}
                <RegistrationForm />
            </Pane>

            <Pane className={`form forgot`} flex={5}>
                {/* <h3 className="title">Authentication Issues</h3> */}
                <ForgotForm />
            </Pane>

            <Pane className={`form toggles`} flex={5}>
                {/* Login */}
                <Button className="login" onClick={() => setAuthUIState("login")}>Login</Button>

                {/* Register */}
                {/* <Button className="register" onClick={() => setAuthUIState("register")}>Register</Button> */}

                {/* Register */}
                <Text className="forgot" onClick={() => setAuthUIState("forgot")}>Forgot Password?</Text>
                {/* <Text className="forgot" onClick={continueAsGuest}>Continue as guest</Text> */}

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

export default Auth
