import { Amounts, TalerExchangeApi, TalerProtocolTimestamp, TranslatedString } from "@gnu-taler/taler-util";
import { LocalNotificationBanner, useLocalNotification, useTranslationContext } from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useExchangeApiContext } from "../context/config.js";
import { useOfficer } from "../hooks/useOfficer.js";
import { Pages } from "../pages.js";
import { AntiMoneyLaunderingForm, allForms } from "./AntiMoneyLaunderingForm.js";
import { HandleAccountNotReady } from "./HandleAccountNotReady.js";

export function NewFormEntry({
  account,
  type,
}: {
  account?: string;
  type?: string;
}): VNode {
  const { i18n } = useTranslationContext()
  const officer = useOfficer();
  const { api } = useExchangeApiContext()
  const [notification, notify, handleError] = useLocalNotification()

  if (!account) {
    return <div>no account</div>;
  }
  if (!type) {
    return <SelectForm account={account} />;
  }
  if (officer.state !== "ready") {
    return <HandleAccountNotReady officer={officer} />;
  }

  return (
    <Fragment>
      <LocalNotificationBanner notification={notification} />

      <AntiMoneyLaunderingForm
        account={account}
        formId={type}
        onSubmit={async (justification, new_state, new_threshold) => {

          const decision: Omit<TalerExchangeApi.AmlDecision, "officer_sig"> = {
            justification: JSON.stringify(justification),
            decision_time: TalerProtocolTimestamp.now(),
            h_payto: account,
            new_state,
            new_threshold: Amounts.stringify(new_threshold),
            kyc_requirements: undefined
          }
          await handleError(async () => {
            const resp = await api.addDecisionDetails(officer.account, decision);
            if (resp.type === "ok") {
              window.location.href = Pages.cases.url;
              return;
            }
            switch (resp.case) {
              case "unauthorized": return notify({
                type: "error",
                title: i18n.str`Wrong credentials for "${officer.account}"`,
                description: resp.detail.hint as TranslatedString,
                debug: resp.detail,
              })
              case "officer-or-account-not-found": return notify({
                type: "error",
                title: i18n.str`Officer or account not found`,
                description: resp.detail.hint as TranslatedString,
                debug: resp.detail,
              })
              case "officer-disabled-or-recent-decision": return notify({
                type: "error",
                title: i18n.str`Officer disabled or more recent decision was already submitted.`,
                description: resp.detail.hint as TranslatedString,
                debug: resp.detail,
              })
            }
          })
        }}
      />
    </Fragment>
  );
}

function SelectForm({ account }: { account: string }) {
  return (
    <div>
      <pre>New form for account: {account}</pre>
      {allForms.map((form, idx) => {
        return (
          <a
            href={Pages.newFormEntry.url({ account, type: form.id })}
            class="m-4 block rounded-md w-fit border-0 p-3 py-2 text-center text-sm bg-indigo-700 text-white shadow-sm hover:bg-indigo-600"
          >
            {form.label}
          </a>
        );
      })}
    </div>
  );
}
