/*
 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/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */

import {
  assertUnreachable,
  Duration,
  HttpStatusCode,
  LoginTokenRequest,
  LoginTokenScope,
  TranslatedString,
} 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 { SolveMFAChallenges } from "../../components/SolveMFA.js";
import { useSessionContext } from "../../context/session.js";
import { FormProvider } from "../../components/form/FormProvider.js";
import { doAutoFocus } from "../../components/form/Input.js";
import { Tooltip } from "../../components/Tooltip.js";
import { maybeTryFirstMFA } from "../instance/accounts/create/CreatePage.js";

const TALER_SCREEN_ID = 79;

interface Props {
  showCreateAccount?: boolean;
  focus?: boolean;
}

export const TEMP_TEST_TOKEN = (description: TranslatedString) =>
  ({
    scope: LoginTokenScope.All,
    duration: Duration.toTalerProtocolDuration(Duration.fromMilliseconds(100)),
    description,
  }) as LoginTokenRequest;

export const FOREVER_REFRESHABLE_TOKEN = (description: TranslatedString) =>
  ({
    scope: LoginTokenScope.All_Refreshable,
    duration: Duration.toTalerProtocolDuration(Duration.getForever()),
    description,
  }) as LoginTokenRequest;

export function LoginPage({ showCreateAccount, focus }: Props): VNode {
  const [password, setPassword] = useState("");

  const { state, lib, logIn, getInstanceForUsername, config } =
    useSessionContext();
  const [username, setUsername] = useState(
    showCreateAccount ? "" : state.instance,
  );

  const { i18n } = useTranslationContext();
  const [hidePassword, setHidePassword] = useState(true);

  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const mfa = useChallengeHandler();

  const login = safeFunctionHandler(
    i18n.str`login`,
    async (usr: string, pwd: string, challengeIds: string[]) => {
      const api = getInstanceForUsername(usr);
      const resp = await api.createAccessToken(
        usr,
        pwd,
        FOREVER_REFRESHABLE_TOKEN(i18n.str`Logged in`),
        { challengeIds },
      );
      if (resp.type === "fail" && resp.case === HttpStatusCode.Accepted) {
        await maybeTryFirstMFA(lib.instance, mfa, resp.body);
      }
      return resp;
    },
    !username || !password ? undefined : [username, password, []],
  );
  login.onSuccess = (success, usr) => {
    logIn(usr, success.access_token);
  };
  login.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Accepted:
        return undefined;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Wrong password.`;
      case HttpStatusCode.NotFound:
        return i18n.str`The account doesn't exist.`;
      default:
        assertUnreachable(fail);
    }
  };
  const retry = login.lambda((ids: string[]) => [
    login.args![0],
    login.args![1],
    ids,
  ]);

  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        initial={mfa.initial}
        onCompleted={retry}
        onCancel={mfa.doCancelChallenge}
        focus
      />
    );
  }

  return (
    <div>
      <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>Login required</i18n.Translate>
                </p>
              </header>
              <FormProvider>
                <section
                  class="modal-card-body"
                  style={{
                    borderRight: "1px solid",
                    borderLeft: "1px solid",
                    borderTop: 0,
                    borderBottom: 0,
                    overflow: "hidden",
                  }}
                >
                  <div class="field is-horizontal">
                    <div class="field-label is-normal">
                      <label class="label">
                        <i18n.Translate>Username</i18n.Translate>
                        <Tooltip text={i18n.str`Instance name.`}>
                          <i class="icon mdi mdi-information" />
                        </Tooltip>
                      </label>
                    </div>
                    <div class="field-body">
                      <div class="field">
                        <p class="control is-expanded">
                          <input
                            class="input"
                            type="text"
                            ref={focus ? doAutoFocus : undefined}
                            // placeholder={i18n.str`instance name`}
                            name="username"
                            autoComplete="username"
                            value={username}
                            onInput={(e): void =>
                              setUsername(e?.currentTarget.value)
                            }
                          />
                        </p>
                      </div>
                    </div>
                  </div>
                  <div class="field is-horizontal">
                    <div class="field-label is-normal">
                      <label class="label">
                        <i18n.Translate>Password</i18n.Translate>
                        <Tooltip text={i18n.str`Instance password.`}>
                          <i class="icon mdi mdi-information" />
                        </Tooltip>
                      </label>
                    </div>
                    <div class="field-body">
                      <div class="field has-addons">
                        <p class="control is-expanded">
                          <input
                            class="input"
                            type={hidePassword ? "password" : "text"}
                            // placeholder={i18n.str`current password`}
                            name="token"
                            autoComplete="current-password"
                            value={password}
                            onInput={(e): void =>
                              setPassword(e?.currentTarget.value)
                            }
                          />
                        </p>
                        <div
                          class="control"
                          style={{ cursor: "pointer" }}
                          onClick={() => {
                            setHidePassword((h) => !h);
                          }}
                        >
                          <a class="button is-static point">
                            {hidePassword ? (
                              <i class="icon mdi mdi-eye-off" />
                            ) : (
                              <i class="icon mdi mdi-eye" />
                            )}
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                </section>
                <footer
                  class="modal-card-foot "
                  style={{
                    justifyContent: "space-between",
                    border: "1px solid",
                    borderTop: 0,
                  }}
                >
                  {!config.have_self_provisioning ? (
                    <div />
                  ) : (
                    <a
                      href={
                        !username || username === "admin"
                          ? undefined
                          : `#/account/reset/${username}`
                      }
                      class="button "
                      disabled={!username || username === "admin"}
                    >
                      <i18n.Translate>Forgot password</i18n.Translate>
                    </a>
                  )}
                  <ButtonBetterBulma onClick={login} type="submit">
                    <i18n.Translate>Confirm</i18n.Translate>
                  </ButtonBetterBulma>
                </footer>
              </FormProvider>
            </div>
          </div>
          {!showCreateAccount ? undefined : (
            <div style={{ marginTop: 8 }}>
              <a href={"#/account/new"} class="has-icon">
                <i class="icon mdi mdi-account-plus" />
                <span class="menu-item-label">
                  <i18n.Translate>Create new account</i18n.Translate>
                </span>
              </a>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
