import React, { useEffect } from "react"

import chromajs from '@chromaplatform/chromajs'

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


/* Views & Components */


/* Media */
import './supply-code.css'
// import logo from '../../../assets/img/Microdose-Text-Black-V1.png'



const SupplyCodeRedeemForm = (props) => {
    const [status, setStatus] = React.useState({status: "ready"})
    const [supplyCode, setSupplyCode] = React.useState("")
    const [supplyCodeValue, setSupplyCodeValue] = React.useState("")
    const [redeemCode, setRedeemCode] = React.useState(false)
    const [verifyCode, setVerifyCode] = React.useState(false)

    // supplyCodeData - use variable for whatever the type's value is
    const [supplyCodeData, setSupplyCodeData] = React.useState({
        type: "",
        title: "",
        message: "",
        uses: 0
    })

    /* Handle Async verify */
    useEffect(() => {    
        async function verifyCode() {
            // Skip if code empty
            if(supplyCode !== ""){
                const endpoint = `supply/code/verify/${supplyCode}`
                const data = await chromajs.query(endpoint, {})
    
                if(data.data.message === "INVALID"){
                    // Invalid seed code
                    setStatus({status: "error", error: "INVALID SEEDCODE"})
                } else {
                    // Valid seed code
                    const result = data.data // routing to .data
                    setSupplyCodeData({type: result.type, title: result.title, message: result.message, uses: result.uses})

                    // or display code data & redeem button
                    setStatus({status: "verified"})
                }
            }
        }

        async function redeem() {
            const endpoint = `supply/code/redeem/${supplyCode}`
            const data = await chromajs.query(endpoint, {})

            if(data.message === "INVALID"){
                // Invalid seed code
                setStatus({status: "error", error: "INVALID SEEDCODE"})
            } else {
                // Valid seed code
                if(data.data.status === "success"){
                    setStatus({status: "ready"})

                    const result = {
                        status: "success",
                        result: data.data
                    }

                    // Dispatch Event
                    global.dispatchEvent(new CustomEvent('/seedcode/redeem', { bubbles: true, detail: result }))
                } else {
                    const result = {
                        status: "failed"
                    }

                    global.dispatchEvent(new CustomEvent('/seedcode/redeem', { bubbles: true, detail: result }))
                    
                    setStatus({status: "error", error: "INVALID SEEDCODE"})
                }
            }
        }
    
        if(verifyCode){
            verifyCode()
        }

        if(redeemCode){
            redeem()
        }

        return () => {}
    }, [supplyCode, redeemCode, verifyCode]) // Pass supplyCode to method

    const handleSupplyCodeVerify = (e) => {
        setStatus({status: "pending"})

        // Triggers effect above to verifySeedCode
        setSupplyCode(supplyCodeValue)
        setVerifyCode(true)

        // TODO: Testing moving this
        // // or display code data & redeem button
        // setStatus({status: "verified"})
    }

    const handleSupplyCodeRedeem = (e) => {
        setStatus({status: "pending"})
        setRedeemCode(true)
    }

    /* Submit form on [enter] click */
    const handleEnterClick = (event) => {
        if(event.key === 'Enter'){
            event.target.blur()
            handleSupplyCodeVerify()
        }
    }


    return (
        <Pane className={`supply-code-form ${status.status}`}>
            {/* MOVE THIS INTO CHILD COMPONENT */}
            <Pane className="verify-code container">
                {/* Feedback */}
                {status.status !== "error" ? "" : <Alert
                        appearance="card"
                        intent="danger"
                        title={status.error}
                    />}

                {/* Seedcode */}
                <Pane>
                    <TextInput
                        name="text-input-supply-code"
                        className="input"
                        placeholder="Seed Code"
                        onKeyPress={handleEnterClick}
                        onChange={event => setSupplyCodeValue(event.target.value)}
                    />
                </Pane>

                {/* Enter Button */}
                <Button
                    appearance="primary" 
                    className="verify-button"
                    disabled={status.status === "pending" ? true : false} 
                    onClick={() => handleSupplyCodeVerify()}>

                    ENTER
                </Button>

                <Pane className="clear" />
            </Pane> {/* End Verify */}

            {/* MOVE THIS INTO CHILD COMPONENT */}
            <Pane className="redeem-code container">
                {/* Code Image - Make this dynamic & w/ dark/light mode */}
                {/* <img src={logo} className="code-logo" alt="logo" /> */}

                {/* Feedback */}
                {status.status !== "error" ? "" : <Alert
                        appearance="card"
                        intent="danger"
                        title={status.error}
                    />}
                
                {/* Code Data */}
                <Pane className="data-container">
                    <Pane className="row">
                        <Text className="data variable">CODE</Text>
                        <Text className="data variable value">{supplyCode}</Text>   
                    </Pane>

                    <Pane className="row">
                        <Text className="data type">TYPE</Text>
                        <Text className="data type value">{supplyCodeData.type}</Text>
                    </Pane>

                    <Pane className="row">
                        <Text className="data app">APP</Text>
                        <Text className="data app value">{supplyCodeData.title}</Text>
                    </Pane>

                    <Pane className="row">
                        <Text className="data uses">REMAINING USES</Text>
                        <Text className="data uses value">{supplyCodeData.uses}</Text>
                    </Pane>
                </Pane>

                {/* Redeem Button */}
                <Button
                    appearance="primary"
                    className="redeem-button"
                    disabled={status.status === "pending" ? true : false}
                    onClick={() => handleSupplyCodeRedeem()}>

                    Redeem Code
                </Button>

                <Pane className="clear" />
            </Pane> {/* End Redeem */}

        </Pane>
    );
}

export default SupplyCodeRedeemForm
