/*
 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 {
  AbsoluteTime,
  ChallengeResponse,
  HttpStatusCode,
  TalerMerchantApi,
} from "@gnu-taler/taler-util";
import {
  Time,
  useChallengeHandler,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { NotificationCard } from "../../../../components/menu/index.js";
import { useSessionContext } from "../../../../context/session.js";
import { Notification } from "../../../../utils/types.js";
import { CreatePage } from "./CreatePage.js";
import { ConfirmModal, Row } from "../../../../components/modal/index.js";
import { SolveMFAChallenges } from "../../../../components/SolveMFA.js";

export type Entity = TalerMerchantApi.LoginTokenRequest;
interface Props {
  onBack?: () => void;
  onConfirm: () => void;
}

export default function AccessTokenCreatePage({
  onConfirm,
  onBack,
}: Props): VNode {
  const { state, lib } = useSessionContext();
  const [notif, setNotif] = useState<Notification | undefined>(undefined);
  const { i18n } = useTranslationContext();

  const [ok, setOk] = useState<{ token: string; expiration: AbsoluteTime }>();
  const mfa = useChallengeHandler();

  const [doCreate, repeatCreate] = mfa.withMfaHandler(
    ({ challengeIds, onChallengeRequired }) =>
      async function doCreateImpl(pwd:string, request: Entity) {
        try {
          const resp = await lib.instance.createAccessToken(
            state.instance,
            pwd,
            request,
            { challengeIds },
          );
          if (resp.type === "fail") {
            if (resp.case === HttpStatusCode.Accepted) {
              onChallengeRequired(resp.body);
              return;
            }
            setNotif({
              message: i18n.str`Could not create access token`,
              type: "ERROR",
              description: resp.detail?.hint,
            });
            return;
          }
          setOk({
            expiration: AbsoluteTime.fromProtocolTimestamp(
              resp.body.expiration,
            ),
            token: resp.body.access_token,
          });
        } catch (error) {
          setNotif({
            message: i18n.str`Could not create access token`,
            type: "ERROR",
            description: error instanceof Error ? error.message : String(error),
          });
        }
      },
  );

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

  return (
    <Fragment>
      <NotificationCard notification={notif} />
      {!ok ? undefined : (
        <ConfirmModal
          // label={`Confirm`}
          active
          onConfirm={() => onConfirm()}
          onCancel={() => {}}
          noCancelButton
          description={i18n.str`Access token created`}
        >
          <div class="table-container">
            <table>
              <tbody>
                <tr>
                  <td colSpan={3}>
                    <i18n.Translate>
                      Copy the access token velue and save it because you won't
                      be able to get it again.
                    </i18n.Translate>
                  </td>
                </tr>
                <Row name={i18n.str`Token`} value={ok.token} literal />

                <tr>
                  <td colSpan={3}>
                    {AbsoluteTime.isNever(ok.expiration) ? (
                      <i18n.Translate>
                        This token will never expire
                      </i18n.Translate>
                    ) : (
                      <i18n.Translate>
                        This token will be available until{" "}
                        <Time
                          format="dd/MM/yyyy HH:mm:ss"
                          timestamp={ok.expiration}
                        />
                      </i18n.Translate>
                    )}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </ConfirmModal>
      )}
      <CreatePage onBack={onBack} onCreate={doCreate} />
    </Fragment>
  );
}
