import React, {useEffect, useState} from "react";
import { connect } from 'react-redux';
import CryptoJS from 'crypto-js';
import { getContract, getWalletAccount, getWalletBalance, getWalletIsLoading, getWeb3 } from "../../redux/reducers";
import {Button, Loader} from 'semantic-ui-react';
import {connectWallet, getTokenBalance} from '../../redux/actions';
import './stamps.scss';
import { useHistory } from "react-router";

function Stamps({web3, contract, account, balance, walletLoading, connectWallet, getTokenBalance}) {
    const [createLoading, setCreateLoading] = useState(false);
    const [redeemLoading, setRedeemLoading] = useState(false);
    const history = useHistory();
    
    useEffect(() => {
        if(!account && web3) {
            connectWallet(web3, contract);
        } 
    }, [account, web3, contract, connectWallet, walletLoading, balance, createLoading]);

    function renderStamps() {
        var stamps = [];
        for(let i = 0; i < 10; i++) {
            stamps.push(
                <div className={`stamp ${i < balance ? 'full' : 'empty'}`} key={i}>
                    <div className='number'>{i}</div>
                    <img src="/beer.png" alt="Beer Stamp" />
                </div>
            );
        }
        return stamps;
    }

    async function addStamp() {
        if(parseInt(balance) >= 10) {
            return;
        }
        setCreateLoading(true);
        const tokenId = "0x" + CryptoJS.SHA256(account + balance).toString();
        console.log("balance: " + balance);
        console.log(tokenId);
        contract.methods.mint(account, tokenId).send({from: account}).then((res) => {
            getTokenBalance(account, contract);
            setCreateLoading(false);
        }).catch((err) => {
            setCreateLoading(false);
            console.log(err)
        });
    }

    function redeemStamps() {
        if(parseInt(balance) !== 10) {
            return;
        }
        setRedeemLoading(true);
        let tokenIds = [];
        for(let i = 0; i < balance; i++) {
            
            tokenIds.push("0x" + CryptoJS.SHA256(account + i).toString());
            
        }
        console.log(tokenIds);
        contract.methods.burnAll(account, tokenIds).send({from: account}).then((res) => {
            getTokenBalance(account, contract);
            setRedeemLoading(false);
            history.push('/redeem');
        }).catch((err) => {
            setRedeemLoading(false);
            console.log(err);
        });
    }

    function getAddStampLabel() {
        if(balance < 10) {
            return 'Add Stamp';
        } else {
            return 'You Card is full...';
        }
    }

    function getRedeemLabel() {
        if(balance < 9) {
            return `Add ${10 - balance} more Stamps...`;
        } else if(parseInt(balance) === 9) {
            return 'Add 1 more Stamp...';
        } else {
            return 'Redeem Stamp Card';
        }
    }

    return (
        <div id="stamps">
            <h1>Your Beer-Stamps</h1>
            {walletLoading || !account ? (
                <Loader active inline='centered' size='huge' />
            ) : (
                <>
                    <div className='add-stamp'>
                        <Button disabled={parseInt(balance) === 10} loading={createLoading} onClick={() => addStamp()}>{getAddStampLabel()}</Button>
                    </div>
                <div className='stamps'>
                    {parseInt(balance) === 10 && <div class='full-card'>Stamp-Card full</div>}
                    {renderStamps()}
                </div>
                    <div className='redeem'>
                        <Button disabled={parseInt(balance) !== 10} loading={redeemLoading} onClick={() => redeemStamps()}>{getRedeemLabel()}</Button>
                    </div>
                </>
            )}
        </div>
    );
}

const mapStateToProps = (state) => ({
    web3: getWeb3(state),
    contract: getContract(state),
    account: getWalletAccount(state),
    balance: getWalletBalance(state),
    walletLoading: getWalletIsLoading(state)
});
  
const mapDispatchToProps = {
    connectWallet,
    getTokenBalance
};

export default connect(mapStateToProps, mapDispatchToProps)(Stamps);