import React from 'react';
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
} from 'chart.js';
import faker from 'faker';
import { Line } from 'react-chartjs-2';
import { StyleSheet, View } from 'react-native';
import { observer } from 'mobx-react';
import PropTypes from 'prop-types';
import Background from '../component/background';
import MainContent from '../component/main-content';
import { DetailField } from '../component/field';
import Modal from '../component/modal';
import { color } from '../component/style';
//import LightningBoltOrangeIcon from '../asset/icon/lightning-bolt-orange';
import { GlasButton } from '../component/button';
import store from '../store';
//import { DEFAULT_FIAT } from '../config';

//import Algorand from '../chains/algo/algo.js';
//import Icon from '../component/icon';
//import algosdk from "algosdk";
//import { Asset,TinymanMainnetClient } from 'tinyman-ts-sdk';

ChartJS.register(
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

const days = 30;
const labels = [];
for (let i = 0; i < days; i++) {
  labels.push(i);
}
//const labels = ['30', '29', '28', '27', '26', '25', '24', '23', '22', '21', '20', '19', '18', '17', '16', '15', '14', '13', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1'];
/*
async function doSwap(mne){

const MNEMONIC = mne;
const ACCOUNT = algosdk.mnemonicToSecretKey(MNEMONIC);
const WALLET_ADDRESS = ACCOUNT.addr;
const SECRET_KEY = ACCOUNT.sk;

const client = new algosdk.Algodv2('','https://api.algoexplorer.io','',{'user-agent':'algo-sdk'});

//Initialize Tinyman's Mainnet Client
const TinymanClient = new TinymanMainnetClient(client,WALLET_ADDRESS);

//Fetch the Assets from the network
const A1 = await new Asset(0).fetch(client);       //ALGO
const A2 = await new Asset(31566704).fetch(client); //USDC

//Get the Pool for this Asset pair
const POOL = await TinymanClient.fetch_pool(A1,A2,true);

//Get a Fixed Input Swap Quote
const FIXED_INPUT_SWAP = await POOL.fetch_fixed_input_swap_quote(A1.AssetAmount(1000000),0.01);

//Prepare the Swap Transactions
const TXNS = await POOL.prepare_swap_transactions(
    FIXED_INPUT_SWAP.amount_in_with_slippage(),
    FIXED_INPUT_SWAP.amount_out_with_slippage(),
    'fixed-input',
    WALLET_ADDRESS
);

//Sign the Transactions
TXNS.sign_with_private_key(WALLET_ADDRESS,SECRET_KEY);

//Submit the transactions and wait for confirmation
await TXNS.submit(client,true);

}
*/
function newPoolSize(day) {
  var size =
    faker.datatype.number({ min: 1000, max: 1500 }) /
    (Math.log(10 + parseInt(day)) *
      faker.datatype.number({ min: 0.65, max: 0.95 }));
  return size;
}

export const perfData = {
  labels,
  datasets: [
    {
      label: 'income',
      data: labels.map(() => faker.datatype.number({ min: 400, max: 1000 })),
      borderColor: 'rgb(99, 255, 221)',
      backgroundColor: 'rgba(99, 255, 221, 0.25)',
    },
    {
      label: 'expenses',
      data: labels.map(() => faker.datatype.number({ min: 200, max: 500 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.4)',
    },
    {
      label: 'pool (,00)',
      data: labels.map(newPoolSize),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

const styles = StyleSheet.create({
  content: {
    justifyContent: 'center',
  },
  topIcon: {
    height: 72,
    width: 72,
    backgroundColor: '#0f5f76',
    borderRadius: 20,
    padding: 10,
  },
  btnIcon: {
    height: 32,
    width: 32,
    margin: 20,
  },
  perfChart: {
    height: 180,
    width: 180,
    margin: 5,
  },
  chart: {
    margin: '10px',
  },
});

const iconType = t => {
  /*
  if (tx.type === 'algorand') {
     tx.status === 'complete' ? 'success' : 'info';
  } else {
    tx.status === 'confirmed' ? 'success' : 'info';
  }
  
  <Icon
        image={iconType(store.selectedPool.type)}
        style={styles.topIcon}
      />
      
  */
  return require('../asset/icon/' + t + '.png');
};
/*
function getPoolShare(type, aID1, aID2, address) {
 
Algorand.checkPoolStatus()
 
 }
*/
async function dataGen(store, options, grpc) {
  perfData.datasets[0].data = labels.map(() =>
    faker.datatype.number({ min: 400, max: 1000 })
  );

  perfData.datasets[1].data = labels.map(() =>
    faker.datatype.number({ min: 200, max: 500 })
  );
  perfData.datasets[2].data = labels.map(newPoolSize);
  options.plugins.title.text =
    '30d Volume (' + store.settings.fiat.toLowerCase() + ')';
  /*
var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'bootstrap', 70653745, 0, '289:BITS', 'ALGO', 'TTNTINGI6AKN6JBHCAOXVFZN72BAMDNBTHZ3ZRQC3ILAMWONKN7XRRQ6GM' ]);
    //poolStats = poolStats.replace(/'/g, '"').replace(/"{/g, "{").slice(0, -3);
    
    console.log(poolStats);
    
  
  
   store.selectedPool.stats=JSON.parse(poolStats);
 
   console.log(store.settings.chains.algo.account.address);
   var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'poolState', 70232824, 0, 'TTNTINGI6AKN6JBHCAOXVFZN72BAMDNBTHZ3ZRQC3ILAMWONKN7XRRQ6GM' ]);
    
    console.log(poolStats);
  
    
  var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'quote', 70232824, 0 ]);
    
    console.log(poolStats);
    
  
  var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'addLiq', 21582668, 0 , store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 1]);
    
    
    console.log(poolStats);
    
      var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', 70653745, 0, 1, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 1 ]);
 
  
  var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'addLiq', 70653745, 0 , store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 1]);
     
  var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'addLiq', 70653745, 0 , store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 1]);
    
      var poolStats = await grpc.initPyface(['/data/lightning-bits/src/chains/algo/pools.py', 'swap', 75685483 , 0, 10, store.settings.chains.algo.account.address, store.settings.chains.algo.account.mnemonic, 'remove' ]);
    console.log(poolStats);
 */
  //  doSwap(store.settings.chains.algo.account.mnemonic);

  var poolStats = await grpc.initPyface([
    '/data/lightning-bits/src/chains/algo/pools.py',
    'pooling',
    store.selectedPool.assetID,
    0,
    store.settings.chains.algo.account.address,
    store.settings.chains.algo.account.mnemonic,
  ]);
  console.log(poolStats);
}

const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: '30d Volume (' + store.settings.fiat.toLowerCase() + ')',
    },
  },
};
const PoolDetailView = ({ store, grpc, nav, pooladdliq, poolremoveliq }) => (
  <Background color={color.blackDark}>
    <MainContent style={styles.content}>
      <Modal title={store.selectedPool.idName} onClose={() => nav.goPools()}>
        <Line
          meta={dataGen(store, options, grpc)}
          options={options}
          data={perfData}
        />
        <DetailField name={store.selectedPool.title}>
          {store.selectedPool.desc}
        </DetailField>
        <DetailField name="Performance">
          VALUATION:
          {parseInt(store.selectedPool.quoteFiat * 1000) + store.settings.fiat}
          PRICE:
          {parseInt(store.selectedPool.quoteFiat) + store.settings.fiat}
          SHARE:
          {parseInt(store.selectedPool.amount * store.selectedPool.quoteFiat) +
            store.settings.fiat}
        </DetailField>
        {store.selectedPool.memo ? (
          <DetailField name="Note">{store.selectedPool.memo}</DetailField>
        ) : null}
        <DetailField name="Pool">
          CAP: {store.unitLabel}
          FUNDED: 12% INVESTORS: 11 ID: {store.selectedPool.id}:BITS
        </DetailField>
        <DetailField name="Asset Supply">
          TOTAL: 1,000 | OWNED: {store.selectedPool.amount} | CIRCULATING: 30%
          |ID: {store.selectedPool.assetID}
        </DetailField>
        {store.selectedPool.confirmationsLabel ? (
          <DetailField name="Contract">
            POOLERS: {store.selectedPool.confirmationsLabel} | CHAIN:
            {store.selectedPool.typeLabel} | Lock Time: 30 Days
          </DetailField>
        ) : null}
        <SendReceiveButton
          goPay={() => pooladdliq.init()}
          goRequest={() => poolremoveliq.init()}
          store={iconType(store.selectedPool.type)}
        />
      </Modal>
    </MainContent>
  </Background>
);

PoolDetailView.propTypes = {
  grpc: PropTypes.object.isRequired,
  nav: PropTypes.object.isRequired,
  store: PropTypes.object.isRequired,
  pooladdliq: PropTypes.object.isRequired,
  poolremoveliq: PropTypes.object.isRequired,
};

//
// Send Receive Button
//

const bigBtnStyles = StyleSheet.create({
  wrapper: {
    alignSelf: 'stretch',
    flexDirection: 'row',
    marginTop: 80,
    backgroundColor: '#0f5f76',
    borderRadius: 21,
  },
  leftBtn: {
    flex: 1,
    borderTopLeftRadius: 21,
    borderBottomLeftRadius: 21,
    backgroundColor: 'red',
  },
  rightBtn: {
    flex: 1,
    borderTopRightRadius: 21,
    borderBottomRightRadius: 21,
    backgroundColor: 'green',
  },
  boltWrapper: {
    justifyContent: 'center',
    backgroundColor: color.glas,
  },
});

const SendReceiveButton = ({ goRequest, goPay }) => (
  <View style={bigBtnStyles.wrapper}>
    <GlasButton onPress={goRequest} style={bigBtnStyles.leftBtn}>
      Remove Funds
    </GlasButton>
    <View style={bigBtnStyles.boltWrapper}></View>
    <GlasButton onPress={goPay} style={bigBtnStyles.rightBtn}>
      Add Funds
    </GlasButton>
  </View>
);

SendReceiveButton.propTypes = {
  goPay: PropTypes.func.isRequired,
  store: PropTypes.object.isRequired,
  goRequest: PropTypes.func.isRequired,
  nav: PropTypes.object.isRequired,
};

export default observer(PoolDetailView);
