import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { withBurner, BurnerContext, DataProviders } from '@burner-wallet/ui-core';
import { AccountBalanceData } from "@burner-wallet/types";
const logo = require('./white-rabbit-logo-white.png');

const Container = styled.div`
  height: 64px;
  display: flex;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 100;
  padding: 0 32px;
  align-items: center;
`;

const HeaderElement = styled.header`
  display: flex;
  flex-direction: row;
  color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 36px;
  width: 100%;
`;

const Logo = styled.img`
  display: block;
  width: 150px;
  height: 36px;
`;

const BalanceTotal = styled.div``;

interface HeaderProps extends BurnerContext {
  title?: string;
}

const { AccountBalance } = DataProviders;

// TODO: duplicates backendEndpoint from burner-plugin. Probably merge into a single package (plugin + wallet)
const backendEndpoint = process.env.NODE_ENV === "development"
  ? "http://localhost:4000/graphql"
  : "https://be-dashboard.whiterabbit.one/graphql";

const getConfig = async (): Promise<{ factor: number }> => {
  const result = await fetch(backendEndpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query: `{ config { factor } }` }),
  }).then((res) => res.json());
  return result.data.config as { factor: number };
};

const Header: React.FC<HeaderProps> = ({ title, accounts,
assets, actions }) => {
  const [factor, setFactor] = useState<number>(1);
  const [account] = accounts;
  const [asset] = assets;
  
  useEffect(() => {
    getConfig().then(({ factor }) => setFactor(factor));
  }, []);

  return (
  <Container>
    <HeaderElement>
      <Logo src={logo} />
      <AccountBalance
        asset={asset}
        account={account}
        render={(data: AccountBalanceData | null) => {
          const balance = (data != null) ? parseFloat(data.displayMaximumSendableBalance) : 0;
          const factorAdjustedValue = Number(balance * factor).toFixed(2);
          return (
            <BalanceTotal onClick={() => actions.navigateTo('/topup')}>
              €{factorAdjustedValue}
            </BalanceTotal>
          );
        }}
        />
    </HeaderElement>
  </Container>
)};

export default withBurner(Header);
