import React, { useEffect } from "react"

/* Media */
import './supply-code-redeem.css'
// import logoLight from '../../../assets/img/Microdose-Text-White-V1.png'
// import logoDark from '../../../assets/img/Microdose-Text-Black-V1.png'

/* Views & Components */


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

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

/* chroma.js */
import chromajs from '@chromaplatform/chromajs'

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: "", variable: "", uses: ""})

    /* 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, {})

                console.log('--Verify--')
                console.log(data)
    
                if(data.data.message === "INVALID"){
                    // Invalid seed code
                    console.log('VERIFY ERROR CODE: INVALID')
                    setStatus({status: "error", error: "INVALID SEEDCODE"})
                } else {
                    // Valid seed code
                    const result = data.data // routing to .data
                    setSupplyCodeData({type: result.type, variable: result.name, 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, {})

            console.log(data)

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

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

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

                    console.log("REDEEM 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 handleRecieveData = (data) => {
        setSupplyCodeData({type: data.type, variable: data.name, uses: data.uses})
    }

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


    return (
        <Pane className={`supply-code-form ${status.status}`}>
            <Pane className="verify-code">
                {/* Google */}
                <Text className="feedback">Enter Seed Code</Text>

                {/* Feedback */}
                {status.status !== "error" ? "" : <Alert
                        appearance="card"
                        intent="danger"
                        title={status.error}
                    />}

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

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

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

            <Pane className="redeem-code">
                {/* Code Image - Make this dynamic & w/ dark/light mode */}
                {/* <img src={logoDark} className="code-logo" alt="logo" /> */}

                {/* Feedback */}
                {status.status !== "error" ? "" : <Alert
                        appearance="card"
                        intent="danger"
                        title={status.error}
                    />}
                
                {/* Code Data */}
                <Pane className="data-container">
                    <Text className="data type">Code Type:</Text>
                    <Text className="data type value">{supplyCodeData.type}</Text>
                    <br />
                    <Text className="data variable">App:</Text>
                    <Text className="data variable value">{supplyCodeData.variable}</Text>                
                    <br />
                    <Text className="data uses">Remaining Uses:</Text>
                    <Text className="data uses value">{supplyCodeData.uses}</Text>
                    <br />
                </Pane>

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

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


        </Pane>
    );
}

export default SupplyCodeRedeemForm
