/*
 This file is part of GNU Taler
 (C) 2022 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import { Logger, TranslatedString } from "@gnu-taler/taler-util";
import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { ComponentChildren, Fragment, h, VNode } from "preact";
import { StateUpdater, useEffect, useState } from "preact/hooks";
import talerLogo from "../assets/logo-white.svg";
import { LangSelectorLikePy as LangSelector } from "../components/LangSelector.js";
import { useBackendContext } from "../context/backend.js";
import { useBusinessAccountDetails } from "../hooks/circuit.js";
import { bankUiSettings } from "../settings.js";
import { useSettings } from "../hooks/settings.js";
import { ErrorMessage, onNotificationUpdate } from "../hooks/notification.js";

const IS_PUBLIC_ACCOUNT_ENABLED = false;
const GIT_HASH = typeof __GIT_HASH__ !== "undefined" ? __GIT_HASH__ : undefined;
const VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : undefined;

const versionText = VERSION
  ? GIT_HASH
    ? `Version ${VERSION} (${GIT_HASH.substring(0, 8)})`
    : VERSION
  : "";

const logger = new Logger("BankFrame");

function MaybeBusinessButton({
  account,
  onClick,
}: {
  account: string;
  onClick: () => void;
}): VNode {
  const { i18n } = useTranslationContext();
  const result = useBusinessAccountDetails(account);
  if (!result.ok) return <Fragment />;
  return (
    <div class="some-space">
      <a
        href="#"
        class="pure-button pure-button-primary"
        onClick={(e) => {
          e.preventDefault();
          onClick();
        }}
      >{i18n.str`Business Profile`}</a>
    </div>
  );
}

export function BankFrame({
  children,
  goToBusinessAccount,
}: {
  children: ComponentChildren;
  goToBusinessAccount?: () => void;
}): VNode {
  const { i18n } = useTranslationContext();
  const backend = useBackendContext();
  const [settings, updateSettings] = useSettings();

  const demo_sites = [];
  for (const i in bankUiSettings.demoSites)
    demo_sites.push(
      <a href={bankUiSettings.demoSites[i][1]}>
        {bankUiSettings.demoSites[i][0]}
      </a>,
    );

  return (
    <Fragment>
      <header
        class="demobar"
        style="display: flex; flex-direction: row; justify-content: space-between;"
      >
        <a href="#main" class="skip">{i18n.str`Skip to main content`}</a>
        <div style="max-width: 50em; margin-left: 2em;">
          <h1>
            <span class="it">
              <a href="/">{bankUiSettings.bankName}</a>
            </span>
          </h1>
          {maybeDemoContent(
            <p>
              {IS_PUBLIC_ACCOUNT_ENABLED ? (
                <i18n.Translate>
                  This part of the demo shows how a bank that supports Taler
                  directly would work. In addition to using your own bank
                  account, you can also see the transaction history of some{" "}
                  <a href="/public-accounts">Public Accounts</a>.
                </i18n.Translate>
              ) : (
                <i18n.Translate>
                  This part of the demo shows how a bank that supports Taler
                  directly would work.
                </i18n.Translate>
              )}
            </p>,
          )}
        </div>
        <a href="https://taler.net/">
          <img
            src={talerLogo}
            alt={i18n.str`Taler logo`}
            height="100"
            width="224"
            style="margin: 2em 2em"
          />
        </a>
      </header>
      <div style="display:flex; flex-direction: column;" class="navcontainer">
        <nav class="demolist">
          {maybeDemoContent(<Fragment>{demo_sites}</Fragment>)}
          <div class="right">
            <LangSelector />
          </div>
        </nav>
      </div>
      <section id="main" class="content">
        <StatusBanner />
        {backend.state.status === "loggedIn" ? (
          <div class="top-right">
            {goToBusinessAccount && !backend.state.isUserAdministrator ? (
              <MaybeBusinessButton
                account={backend.state.username}
                onClick={goToBusinessAccount}
              />
            ) : undefined}
            <div class="some-space">
              <a
                href="#"
                class="pure-button logout-button"
                onClick={() => {
                  backend.logOut();
                  updateSettings("currentWithdrawalOperationId", undefined);
                }}
              >{i18n.str`Logout`}</a>
            </div>
          </div>
        ) : null}
        {children}
      </section>
      <section id="footer" class="footer">
        <div class="footer">
          <hr />
          <div>
            <p>
              You can learn more about GNU Taler on our{" "}
              <a href="https://taler.net">main website</a>.
            </p>
          </div>
          <div style="flex-grow:1" />
          <p>
            Copyright &copy; 2014&mdash;2022 Taler Systems SA. {versionText}
          </p>
        </div>
      </section>
    </Fragment>
  );
}

function maybeDemoContent(content: VNode): VNode {
  if (bankUiSettings.showDemoNav) {
    return content;
  }
  return <Fragment />;
}

export function ErrorBannerFloat({
  error,
  onClear,
}: {
  error: ErrorMessage;
  onClear?: () => void;
}): VNode {
  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        zIndex: 200,
        width: "90%",
      }}
    >
      <ErrorBanner error={error} onClear={onClear} />
    </div>
  );
}

function ErrorBanner({
  error,
  onClear,
}: {
  error: ErrorMessage;
  onClear?: () => void;
}): VNode {
  return (
    <div
      class="informational informational-fail"
      style={{
        marginTop: 8,
        paddingLeft: 16,
        paddingRight: 16,
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <p>
          <b>{error.title}</b>
        </p>
        <div style={{ marginTop: "auto", marginBottom: "auto" }}>
          {onClear && (
            <input
              type="button"
              class="pure-button"
              value="Clear"
              onClick={(e) => {
                e.preventDefault();
                onClear();
              }}
            />
          )}
        </div>
      </div>
      <p>{error.description}</p>
    </div>
  );
}

function StatusBanner(): VNode | null {
  const [info, setInfo] = useState<TranslatedString>();
  const [error, setError] = useState<ErrorMessage>();
  useEffect(() => {
    return onNotificationUpdate((newValue) => {
      if (newValue === undefined) {
        setInfo(undefined);
        setError(undefined);
      } else {
        if (newValue.type === "error") {
          setError(newValue.error);
        } else {
          setInfo(newValue.info);
        }
      }
    });
  }, []);
  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        zIndex: 200,
        width: "90%",
      }}
    >
      {!info ? undefined : (
        <div
          class="informational informational-ok"
          style={{ marginTop: 8, paddingLeft: 16, paddingRight: 16 }}
        >
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <p>
              <b>{info}</b>
            </p>
            <div>
              <input
                type="button"
                class="pure-button"
                value="Clear"
                onClick={async () => {
                  setInfo(undefined);
                }}
              />
            </div>
          </div>
        </div>
      )}
      {!error ? undefined : (
        <ErrorBanner
          error={error}
          onClear={() => {
            setError(undefined);
          }}
        />
      )}
    </div>
  );
}
