import { Amounts } from "@gnu-taler/taler-util";
import { PaytoWireTransferForm } from "../PaytoWireTransferForm.js";
import { handleNotOkResult } from "../HomePage.js";
import { useAccountDetails } from "../../hooks/access.js";
import { useBackendContext } from "../../context/backend.js";
import { notifyInfo, useTranslationContext } from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";

export function AdminAccount({ onRegister }: { onRegister: () => void }): VNode {
    const { i18n } = useTranslationContext();
    const r = useBackendContext();
    const account = r.state.status === "loggedIn" ? r.state.username : "admin";
    const result = useAccountDetails(account);
  
    if (!result.ok) {
      return handleNotOkResult(i18n, onRegister)(result);
    }
    const { data } = result;
    const balance = Amounts.parseOrThrow(data.balance.amount);
    const debitThreshold = Amounts.parseOrThrow(result.data.debitThreshold);
    const balanceIsDebit = result.data.balance.credit_debit_indicator == "debit";
    const limit = balanceIsDebit
      ? Amounts.sub(debitThreshold, balance).amount
      : Amounts.add(balance, debitThreshold).amount;
    if (!balance) return <Fragment />;
    return (
      <Fragment>
        <section id="assets">
          <div class="asset-summary">
            <h2>{i18n.str`Bank account balance`}</h2>
            {!balance ? (
              <div class="large-amount" style={{ color: "gray" }}>
                Waiting server response...
              </div>
            ) : (
              <div class="large-amount amount">
                {balanceIsDebit ? <b>-</b> : null}
                <span class="value">{`${Amounts.stringifyValue(balance)}`}</span>
                &nbsp;
                <span class="currency">{`${balance.currency}`}</span>
              </div>
            )}
          </div>
        </section>
        <PaytoWireTransferForm
          focus
          limit={limit}
          onSuccess={() => {
            notifyInfo(i18n.str`Wire transfer created!`);
          }}
          onCancel={undefined}
        />
      </Fragment>
    );
  }
  