/*
 This file is part of GNU Taler
 (C) 2021-2024 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 {
  assertUnreachable,
  HttpStatusCode,
  MerchantAuthMethod,
  opFixedSuccess,
  TalerErrorCode,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  useChallengeHandler,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";
import { useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
} from "../../components/form/FormProvider.js";
import { Input } from "../../components/form/Input.js";
import { SolveMFAChallenges } from "../../components/SolveMFA.js";
import { useSessionContext } from "../../context/session.js";
import { FOREVER_REFRESHABLE_TOKEN } from "../login/index.js";
import { undefinedIfEmpty } from "../../utils/table.js";
import { InputPassword } from "../../components/form/InputPassword.js";
import { maybeTryFirstMFA } from "../instance/accounts/create/CreatePage.js";

const TALER_SCREEN_ID = 82;

interface Form {
  password: string;
  repeat: string;
}
interface Props {
  onCancel: () => void;
  id: string;
  onReseted: () => void;
}

export function ResetAccount({
  onCancel,
  onReseted,
  id: instanceId,
}: Props): VNode {
  const { i18n } = useTranslationContext();
  const { state: session, lib, logIn } = useSessionContext();

  const [value, setValue] = useState<Partial<Form>>({
    // password: "asd",
    // repeat: "asd",
  });

  const errors = undefinedIfEmpty<FormErrors<Form>>({
    password: !value.password ? i18n.str`Required` : undefined,
    repeat: !value.repeat
      ? i18n.str`Required`
      : value.password !== value.repeat
        ? i18n.str`Doesn't match`
        : undefined,
  });
  const hasErrors = errors !== undefined;

  function valueHandler(s: (d: Partial<Form>) => Partial<Form>): void {
    const next = s(value);
    const v: Form = {
      password: next.password ?? "",
      repeat: next.repeat ?? "",
    };
    setValue(v);
  }
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const mfa = useChallengeHandler();

  const reset = safeFunctionHandler(
    i18n.str`reset password for self provision`,
    async (password: string, challengeIds: string[]) => {
      const forgot = await lib
        .subInstanceApi(instanceId)
        .instance.forgotPasswordSelfProvision(
          { method: MerchantAuthMethod.TOKEN, password },
          { challengeIds },
        );
      if (forgot.type === "fail" && forgot.case === HttpStatusCode.Accepted) {
        await maybeTryFirstMFA(lib.instance, mfa, forgot.body);
      }
      return forgot;
    },
    hasErrors ? undefined : [value.password!, []],
  );
  reset.onSuccess = (suc) => {
    // logIn(instanceId, suc.access_token);
    onReseted();
  };
  reset.onFail = (fail) => {
    switch (fail.case) {
      case TalerErrorCode.MERCHANT_GENERIC_MFA_MISSING:
        return i18n.str`The instance is not properly configured to allow MFA.`;
      case HttpStatusCode.Accepted:
        return undefined;
      // case HttpStatusCode.Unauthorized:
      //   return i18n.str`Unauthorized.`;
      case HttpStatusCode.Forbidden:
        return i18n.str`Forbidden.`;
      case HttpStatusCode.NotFound:
        return i18n.str`The instance "${instanceId}" was not found.`;
      default:
        assertUnreachable(fail);
    }
  };

  const retry = reset.lambda((ids: string[]) => [reset.args![0], ids]);
  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        onCompleted={retry}
        initial={mfa.initial}
        focus
        onCancel={mfa.doCancelChallenge}
      />
    );
  }

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

      <div class="columns is-centered" style={{ margin: "auto" }}>
        <div class="column is-two-thirds ">
          <div class="modal is-active" style={{ position: "initial" }}>
            <div class="modal-card" style={{ width: "100%", margin: 0 }}>
              <header
                class="modal-card-head"
                style={{ border: "1px solid", borderBottom: 0 }}
              >
                <p class="modal-card-title">
                  <i18n.Translate>
                    Resetting access to the instance "{instanceId}"
                  </i18n.Translate>
                </p>
              </header>
              <FormProvider<Form>
                name="settings"
                errors={errors}
                object={value}
                valueHandler={valueHandler}
              >
                <section
                  class="modal-card-body"
                  style={{ border: "1px solid", borderTop: 0, borderBottom: 0 }}
                >
                  <InputPassword<Form>
                    label={i18n.str`New password`}
                    name="password"
                    expand
                    autoComplete="new-password"
                  />
                  <InputPassword<Form>
                    label={i18n.str`Repeat password`}
                    name="repeat"
                    expand
                    autoComplete="new-password"
                  />
                </section>
                <footer
                  class="modal-card-foot "
                  style={{
                    justifyContent: "space-between",
                    border: "1px solid",
                    borderTop: 0,
                  }}
                >
                  <button type="button" class="button" onClick={onCancel}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </button>
                  <ButtonBetterBulma type="submit" onClick={reset}>
                    <i18n.Translate>Reset</i18n.Translate>
                  </ButtonBetterBulma>
                </footer>
              </FormProvider>
            </div>
          </div>
        </div>
      </div>
    </Fragment>
  );
}
