import React, { Dispatch, SetStateAction, useState, useEffect } from "react";
import { TezosToolkit } from "@taquito/taquito";
import { BeaconWallet } from "@taquito/beacon-wallet";
import config from "./../config";


interface BuyButtonProps {
    Tezos: TezosToolkit,
    FA2address: string,
    sender: string,
    receiver: string,
    amountUsd: number
}

interface CoinGeckoPrice {
    last_updated_at: number;
    usd: number;
    usd_24h_change: number;
    usd_24h_vol: number;
    usd_market_cap: number;
}

const BuyButton = ({
    Tezos,
    FA2address,
    sender,
    receiver,
    amountUsd
}: BuyButtonProps ): JSX.Element => {
    
     const [tezUsd, setTezUsd] = useState<CoinGeckoPrice>(config.defaultTezPrice);
     const [tezPool, setTezPool] = useState<number>(0);
     const [tokenPool, setTokenPool] = useState<number>(0);
     const [fiat2Token, setFiat2Token] = useState<number>(0);
     
    useEffect(() => {
        getTezosPrice();
        getPoolSizes();
    }, [])
    
    // calculate Price in Token
    useEffect(() => {
        if( tezUsd.usd > 0 &&
            tezPool > 0 &&
            tokenPool > 0 ) {
            setFiat2Token( tokenPool / tezPool / tezUsd.usd)
        }
    }, [tezUsd,tezPool,tokenPool])
    
    const getTezosPrice = async (): Promise<void> => {
        // https://www.coingecko.com/en/api#explore-api
        fetch("https://api.coingecko.com/api/v3/simple/price?ids=tezos&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true")
            .then(res => res.json())
            .then(res => setTezUsd(res.tezos))
    }
    
    const getPoolSizes = async (): Promise<void> => {
        fetch(`https://api.tzkt.io/v1/contracts/KT1F3BqwEAoa2koYX4Hz7zJ8xfGSxxAGVT8t/storage`)
            .then(res => res.json())
            .then(item => {
                setTezPool( parseFloat(item.storage.tez_pool) );// / tezMultiplyer;
                setTokenPool( (item.storage.token_pool) );// / tokenMultiplyer;
            }
        )
    }
    
    const buyMethod = async (): Promise<void> => {
        makePayment();
    }
    
    const makePayment = async (): Promise<void> => {
	const contract = await Tezos.wallet.at(FA2address);
	
        const transfer_params = [
            {
                from_: sender,
                txs: [{
                    to_: receiver,
                    token_id:0,
                    amount: amountUsd * fiat2Token
                }]
            }
        ];
        
        const op = await contract.methods.transfer(transfer_params).send();
        await op.confirmation();
    }
    
    return (<div><div className="sd">1 Us Dollar if worth{fiat2Token} Moneyheros</div>
        <div className="buttons">
        
        
            <button
	className="button"
	onClick={buyMethod}
	    >Pay {amountUsd * fiat2Token} Moneyherocoins
        </button>
        </div></div>
    );
};

export default BuyButton; 
