import React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';
import { observer } from 'mobx-react';
import { StyleSheet, View } from 'react-native';
import PropTypes from 'prop-types';
import Background from '../component/background';
import MainContent from '../component/main-content';
import { NamedField } from '../component/field';
import { Header, Title } from '../component/header';
import { CancelButton, BackButton, PillButton } from '../component/button';
import Card from '../component/card';
import LightningBoltIcon from '../asset/icon/lightning-bolt';
import { FormStretcher } from '../component/form';
import {
  BalanceLabel,
  BalanceLabelNumeral,
  BalanceLabelUnit,
} from '../component/label';
import { color } from '../component/style';
import { toSatoshis, toAmount } from '../helper';

ChartJS.register(ArcElement, Tooltip, Legend);

/**
 *send BTC to Pool
 *
 *
 */

async function addToPool(grpc, store, pay, nav) {
  nav.goWait();
  const { settings } = store;
  var amount = toSatoshis(store.payment.amount, settings);
  if (
    parseFloat(store.settings.chains.algo.account.balance) * 1000000 >
    amount * 1.01
  ) {
    console.log('INFO! sufficient BTC in contract. skipping lightning swap...');

    var poolStats = await grpc.initPyface([
      '/data/lightning-bits/src/chains/algo/pools.py',
      'swap',
      store.selectedPool.assetID,
      0,
      amount,
      store.settings.chains.algo.account.address,
      store.settings.chains.algo.account.mnemonic,
      'add',
    ]);
    if (poolStats.includes('confirmed in round')) {
      console.log(
        'INFO! swap completed by contract only! skiping lightning swap.'
      );
      nav.goPayPoolDone();
      return true;
    } else {
      nav.goPaymentFailed();
      return false;
    }
  } else if (store.payment.address != '') {
    //return this._notification.display({ msg: 'INFO! swapping lightning BTC to contract BTC' });
    // first test is contract can complete transaction
    poolStats = await grpc.initPyface([
      '/data/lightning-bits/src/chains/algo/pools.py',
      'swap',
      store.selectedPool.assetID,
      0,
      amount,
      store.settings.chains.algo.account.address,
      store.settings.chains.algo.account.mnemonic,
      'add',
    ]);
    console.log(poolStats);
    if (poolStats.includes('confirmed in round')) {
      console.log(
        'INFO! swap completed by contract only! skiping lightning swap.'
      );
      nav.goPayPoolDone();
      return true;
    }
    const { payment, settings } = store;
    try {
      const request = await grpc.sendCommand('decodePayReq', {
        payReq: store.payment.address,
      });
      payment.amount = toAmount(request.numSatoshis, settings);
      payment.note = request.description;
      /* 
      try{
      const { routes } = await grpc.sendCommand('queryRoutes', {
        pubKey: request.destination,
        amt: request.numSatoshis,
        numRoutes: 1,
      });
      
      payment.fee = toAmount(routes[0].totalFees, settings);
      
      }catch(er){console.error(er)}
     */
      payment.fee = toAmount(16, settings);
      console.log(payment);
      var paymentHash = await pay.payLightning();
      if (paymentHash == undefined) {
        nav.goPaymentFailed();
        return false;
      }

      console.log(paymentHash);
      var pH = btoa(String.fromCharCode.apply(null, paymentHash.paymentHash));
      console.log(pH);
      /*
      const fulfill = await grpc.sendCommand('lookupInvoiceV2', {
        payment_hash: pH,
      });
      console.log(fulfill);
      */
      // then add converted contract satoshis to merchant pool
      poolStats = await grpc.initPyface([
        '/data/lightning-bits/src/chains/algo/pools.py',
        'swap',
        store.selectedPool.assetID,
        0,
        amount,
        store.settings.chains.algo.account.address,
        store.settings.chains.algo.account.mnemonic,
        'add',
      ]);
      console.log(poolStats);
      //this._notification.display({ msg: 'Swap completed!' });
      nav.goPayPoolDone();
      return true;
    } catch (err) {
      console.error(err);
      nav.goPaymentFailed();
    }
  }
}

const shareData = {
  labels: ['Locked', 'Allocated', 'Rewards', 'Others'],
  datasets: [
    {
      label: 'Pool Distribution',
      data: [6, 15, 3, 100],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(0, 0, 0, 0.1)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
      ],
      borderWidth: 1,
    },
  ],
};

const styles = StyleSheet.create({
  balance: {
    marginBottom: 10,
  },
  shareChart: {
    height: 320,
    width: 320,
    margin: 5,
  },
  numeral: {
    color: color.blackText,
  },
  unit: {
    color: color.blackText,
  },
  totalLbl: {
    marginTop: 5,
  },
  note: {
    marginTop: 5,
    borderBottomWidth: 0,
  },
  confirmBtn: {
    marginTop: 20,
  },
});

const PayPoolConfirmView = ({ grpc, store, nav, payment }) => (
  <Background image="purple-gradient-bg">
    <Header shadow color={color.purple}>
      <BackButton onPress={() => nav.goPoolDetail()} />
      <Title title="Pool Payment Confirmation">
        <LightningBoltIcon height={12} width={6.1} />
      </Title>
      <CancelButton onPress={() => nav.goHome()} />
    </Header>
    <MainContent>
      <Card>
        <View style={styles.shareChart}>
          <Pie data={shareData} />
        </View>
        <FormStretcher>
          <BalanceLabel style={styles.balance}>
            <BalanceLabelNumeral style={styles.numeral}>
              {store.paymentAmountLabel}
            </BalanceLabelNumeral>
            <BalanceLabelUnit style={styles.unit}>
              {store.unitLabel}
            </BalanceLabelUnit>
          </BalanceLabel>
          <NamedField name="Slippage">2%</NamedField>
          <NamedField name="Fee">
            {store.paymentFeeLabel} {store.unitLabel}
          </NamedField>
          <NamedField name="Total" style={styles.totalLbl}>
            {store.paymentTotalLabel} {store.unitLabel}
          </NamedField>
          {store.payment.note ? (
            <NamedField name="Note" style={styles.note}>
              {store.payment.note}
            </NamedField>
          ) : null}
        </FormStretcher>
        <PillButton
          style={styles.confirmBtn}
          onPress={async function() {
            await addToPool(grpc, store, payment, nav);
          }}
        >
          Confirm
        </PillButton>
      </Card>
    </MainContent>
  </Background>
);

PayPoolConfirmView.propTypes = {
  grpc: PropTypes.object.isRequired,
  store: PropTypes.object.isRequired,
  nav: PropTypes.object.isRequired,
  payment: PropTypes.object.isRequired,
};

export default observer(PayPoolConfirmView);
