import { TalerCorebankApi, TranslatedString } from "@gnu-taler/taler-util";
import { notifyInfo, useLocalNotification, useTranslationContext } from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { mutate } from "swr";
import { Attention } from "@gnu-taler/web-util/browser";
import { useBankCoreApiContext } from "../../context/config.js";
import { useBackendState } from "../../hooks/backend.js";
import { withRuntimeErrorHandling } from "../../utils.js";
import { assertUnreachable } from "../WithdrawalOperationPage.js";
import { getRandomPassword } from "../rnd.js";
import { AccountForm, AccountFormData } from "./AccountForm.js";
import { ShowLocalNotification } from "@gnu-taler/web-util/browser";

export function CreateNewAccount({
  onCancel,
  onCreateSuccess,
}: {
  onCancel: () => void;
  onCreateSuccess: () => void;
}): VNode {
  const { i18n } = useTranslationContext();
  // const { createAccount } = useAdminAccountAPI();
  const { state: credentials } = useBackendState()
  const token = credentials.status !== "loggedIn" ? undefined : credentials.token
  const { api } = useBankCoreApiContext();

  const [submitAccount, setSubmitAccount] = useState<AccountFormData | undefined>();
  const [notification, notify, handleError] = useLocalNotification()

  async function doCreate() {
    if (!submitAccount || !token) return;
    await handleError(async () => {
      const account: TalerCorebankApi.RegisterAccountRequest = {
        cashout_payto_uri: submitAccount.cashout_payto_uri,
        challenge_contact_data: submitAccount.contact_data,
        internal_payto_uri: submitAccount.payto_uri,
        name: submitAccount.name,
        username: submitAccount.username,//FIXME: not in account data
        password: getRandomPassword(),
      };

      const resp = await api.createAccount(token, account);
      if (resp.type === "ok") {
        mutate(() => true)// clean account list
        notifyInfo(
          i18n.str`Account created with password "${account.password}". The user must change the password on the next login.`,
        );
        onCreateSuccess();
      } else {
        switch (resp.case) {
          case "invalid-phone-or-email": return notify({
            type: "error",
            title: i18n.str`Server replied with invalid phone or email`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case "unauthorized": return notify({
            type: "error",
            title: i18n.str`The rights to perform the operation are not sufficient`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case "username-already-exists": return notify({
            type: "error",
            title: i18n.str`Account username is already taken`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case "payto-already-exists": return notify({
            type: "error",
            title: i18n.str`Account id is already taken`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case "insufficient-funds": return notify({
            type: "error",
            title: i18n.str`Bank ran out of bonus credit.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case "username-reserved": return notify({
            type: "error",
            title: i18n.str`Account username can't be used because is reserved`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          default: assertUnreachable(resp)
        }
      }
    })
  }

  if (!(credentials.status === "loggedIn" && credentials.isUserAdministrator)) {
    return <Attention type="warning" title={i18n.str`Can't create accounts`} onClose={onCancel}>
      <i18n.Translate>Only system admin can create accounts.</i18n.Translate>
    </Attention>
  }

  return (
    <div class="grid grid-cols-1 gap-x-8 gap-y-8 pt-10 md:grid-cols-3 bg-gray-100 my-4 px-4 pb-4 rounded-lg">
      <ShowLocalNotification notification={notification} />

      <div class="px-4 sm:px-0">
        <h2 class="text-base font-semibold leading-7 text-gray-900">
          <i18n.Translate>New business account</i18n.Translate>
        </h2>
      </div>
      <AccountForm
        template={undefined}
        purpose="create"
        onChange={(a) => {
          setSubmitAccount(a);
        }}
      >
        <div class="flex items-center justify-between gap-x-6 border-t border-gray-900/10 px-4 py-4 sm:px-8">
          {onCancel ?
            <button type="button" class="text-sm font-semibold leading-6 text-gray-900"
              onClick={onCancel}
            >
              <i18n.Translate>Cancel</i18n.Translate>
            </button>
            : <div />
          }
          <button type="submit"
            class="disabled:opacity-50 disabled:cursor-default cursor-pointer rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
            disabled={!submitAccount}
            onClick={(e) => {
              e.preventDefault()
              doCreate()
            }}
          >
            <i18n.Translate>Create</i18n.Translate>
          </button>
        </div>

      </AccountForm>
    </div>
  );
}
