import React, {useCallback, useMemo} from 'react';
import Page from '../../components/Page';
import {createGlobalStyle} from 'styled-components';
import {Route, Switch, useRouteMatch} from 'react-router-dom';
import {useWallet} from 'use-wallet';
import UnlockWallet from '../../components/UnlockWallet';
import ExchangeCard from './components/ExchangeCard';
import styled from 'styled-components';
import Spacer from '../../components/Spacer';
import useBondStats from '../../hooks/useBondStats';
import useUnicornFinance from '../../hooks/useUnicornFinance';
import useCashPriceInLastTWAP from '../../hooks/useCashPriceInLastTWAP';
import {useTransactionAdder} from '../../state/transactions/hooks';
import ExchangeStat from './components/ExchangeStat';
import useTokenBalance from '../../hooks/useTokenBalance';
import useBondsPurchasable from '../../hooks/useBondsPurchasable';
import {getDisplayBalance} from '../../utils/formatBalance';
import {BOND_REDEEM_PRICE, BOND_REDEEM_PRICE_BN} from '../../unicorn-finance/constants';
import {Alert} from '@material-ui/lab';
import {roundAndFormatNumber} from '../../0x';

import HomeImage from '../../assets/img/fairybg.gif';
import {Grid, Box, Typography} from '@material-ui/core';
const BackgroundImage = createGlobalStyle`
  body {
    background: url(${HomeImage}) repeat !important;
    background-size: cover !important;
    // background: linear-gradient(90deg, rgba(144,17,105,1) 0%, rgba(95,17,144,1) 100%);
  }
`;

const Bond: React.FC = () => {
  const {account} = useWallet();
  const unicornFinance = useUnicornFinance();
  const addTransaction = useTransactionAdder();
  const bondStat = useBondStats();
  const cashPrice = useCashPriceInLastTWAP();

  const bondsPurchasable = useBondsPurchasable();

  const bondBalance = useTokenBalance(unicornFinance?.MAGICBOND);

  const handleBuyBonds = useCallback(
    async (amount: string) => {
      const tx = await unicornFinance.buyBonds(amount);
      addTransaction(tx, {
        summary: `Buy ${Number(amount).toFixed(2)} MAGICBOND with ${amount} UNICORN`,
      });
    },
    [unicornFinance, addTransaction],
  );

  const handleRedeemBonds = useCallback(
    async (amount: string) => {
      const tx = await unicornFinance.redeemBonds(amount);
      addTransaction(tx, {summary: `Redeem ${amount} MAGICBOND`});
    },
    [unicornFinance, addTransaction],
  );

  const isBondRedeemable = useMemo(() => cashPrice.gt(BOND_REDEEM_PRICE_BN), [cashPrice]);
  const isBondPurchasable = useMemo(() => Number(bondStat?.tokenInFtm) < 1.01, [bondStat]);
  const unicornReserves = useMemo(() => (Number(bondStat?.treasuryUnicorns) / 1e18).toFixed(0), [bondStat]);
  const bondSupply = useMemo(() => bondStat?.circulatingSupply, [bondStat]);
  const bondScale = (Number(cashPrice) / 1e18).toFixed(2);

  return (
    <Switch>
      <Page>
        <BackgroundImage />
        {!!account ? (
          <>
            <Typography color="textPrimary" align="center" variant="h3" gutterBottom>
              Buy & Redeem Bonds
            </Typography>
            <Typography color="textPrimary" align="center" variant="h6" gutterBottom style={{marginBottom: '40px'}}>
              Exchange Unicorns for Bonds and burns Unicorn supply<br />Exchange Bonds for Unicorns and earn premiums upon redemption
            </Typography>
            <Box mt={2}>
              <Grid item xs={12} sm={12} justify="center" style={{margin: '18px', display: 'flex'}}>
                <Alert variant="filled" severity="error">
                  <b>Bonds are emitted & premiums redeemable based on last epoch TWAP prices not the current TWAP!</b>
                </Alert>
              </Grid>
            </Box>

            <StyledBond>
              <StyledCardWrapper>
                <ExchangeCard
                  action="Purchase"
                  fromToken={unicornFinance.UNICORN}
                  fromTokenName="UNICORN"
                  toToken={unicornFinance.MAGICBOND}
                  toTokenName="MAGICBOND"
                  priceDesc={
                    !isBondPurchasable
                      ? 'UNICORN is over peg'
                      : getDisplayBalance(bondsPurchasable, 18, 4) + ' MAGICBOND available for purchase'
                  }
                  onExchange={handleBuyBonds}
                />
              </StyledCardWrapper>
              <StyledStatsWrapper>
                <ExchangeStat
                  tokenName="1 UNICORN"
                  description="Last-Hour TWAP Price"
                  //price={Number(unicornStat?.tokenInFtm).toFixed(4) || '-'}
                  price={bondScale || '-'}
                />
                <Spacer size="md" />
                <ExchangeStat
                  tokenName="1 MAGICBOND"
                  description="Bond Price"
                  price={Number(bondStat?.tokenInFtm).toFixed(2) || '-'}
                />

                <Box mt={3}>
                  <Grid item xs={12} sm={12} justify="center" style={{display: 'flex'}}>
                    <Alert variant="filled" severity="error">
                      <b>Unicorn Reserves:</b>{' '}
                      {bondStat?.treasuryUnicorns ? roundAndFormatNumber(Number(unicornReserves), 0) : '-'}
                      <br></br>
                      <b>Bond supply:</b>{' '}
                      {bondStat?.circulatingSupply ? roundAndFormatNumber(Number(bondSupply), 0) : '-'} <br></br>
                      <b>When reserves are {'>'} bond supply debt phase has finished</b>
                    </Alert>
                  </Grid>
                </Box>
              </StyledStatsWrapper>
              <StyledCardWrapper>
                <ExchangeCard
                  action="Redeem"
                  fromToken={unicornFinance.MAGICBOND}
                  fromTokenName="MAGICBOND"
                  toToken={unicornFinance.UNICORN}
                  toTokenName="UNICORN"
                  priceDesc={`${getDisplayBalance(bondBalance)} MAGICBOND Available in wallet`}
                  onExchange={handleRedeemBonds}
                  disabledDescription={!isBondRedeemable ? `Enabled when 1 UNICORN > $${BOND_REDEEM_PRICE}` : null}
                />
              </StyledCardWrapper>
            </StyledBond>
          </>
        ) : (
          <UnlockWallet />
        )}
      </Page>
    </Switch>
  );
};

const StyledBond = styled.div`
  display: flex;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
  }
`;

const StyledCardWrapper = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
  @media (max-width: 768px) {
    width: 80%;
  }
`;

const StyledStatsWrapper = styled.div`
  display: flex;
  flex: 0.8;
  margin: 0 20px;
  flex-direction: column;

  @media (max-width: 768px) {
    width: 80%;
    margin: 16px 0;
  }
`;

export default Bond;
