import { VNode, h } from "preact";
import { AntiMoneyLaunderingForm, allForms } from "./AntiMoneyLaunderingForm.js";
import { Pages } from "../pages.js";
import { NiceForm } from "../NiceForm.js";
import { AbsoluteTime, Amounts, TalerExchangeApi, TalerProtocolTimestamp } from "@gnu-taler/taler-util";
import { AmlExchangeBackend } from "../types.js";
import { useOfficer } from "../hooks/useOfficer.js";
import { HandleAccountNotReady } from "./HandleAccountNotReady.js";
import { useExchangeApiContext } from "../context/config.js";

export function NewFormEntry({
  account,
  type,
}: {
  account?: string;
  type?: string;
}): VNode {
  const officer = useOfficer();

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

  const selectedForm = Number.parseInt(type ?? "0", 10);
  if (Number.isNaN(selectedForm)) {
    return <div>WHAT! {type}</div>;
  }

  const { api } = useExchangeApiContext()

  return (
    <AntiMoneyLaunderingForm
      account={account}
      selectedForm={selectedForm}
      onSubmit={async (justification, new_state, new_threshold) => {
        const decision: TalerExchangeApi.AmlDecision = {
          justification: JSON.stringify(justification),
          decision_time: TalerProtocolTimestamp.now(),
          h_payto: account,
          new_state,
          new_threshold: Amounts.stringify(new_threshold),
          officer_sig: "",
          kyc_requirements: undefined
        }
        api.addDecisionDetails(officer.account, decision);

      }}
    />
  );
}

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: String(idx) })}
            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.name}
          </a>
        );
      })}
    </div>
  );
}
