/*
 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 { AccessToken, HttpStatusCode } 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 { FormProvider } from "../../../components/form/FormProvider.js";
import { Input } from "../../../components/form/Input.js";
import { InputToggle } from "../../../components/form/InputToggle.js";
import { SolveMFAChallenges } from "../../../components/SolveMFA.js";
import { useSessionContext } from "../../../context/session.js";
import { undefinedIfEmpty } from "../../../utils/table.js";

const TALER_SCREEN_ID = 73;

interface Props {
  instanceId: string;
  onDeleted: () => void;
  onBack?: () => void;
}

export function DeletePage({ instanceId, onBack, onDeleted }: Props): VNode {
  type State = {
    // old_token: string;
    name: string;
    purge: boolean;
  };
  const [form, setValue] = useState<Partial<State>>({
    name: "",
    purge: false,
  });
  const { i18n } = useTranslationContext();
  const { state: session, lib, logOut } = useSessionContext();

  const errors = undefinedIfEmpty({
    name: !form.name
      ? i18n.str`Required`
      : form.name !== instanceId
        ? i18n.str`It's not the same.`
        : undefined,
  });

  const hasErrors = errors !== undefined;

  const text = i18n.str`You are deleting the instance with ID "${instanceId}"`;

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

  const remove = safeFunctionHandler(
    (token: AccessToken, purge: boolean, challengeIds: string[]) =>
      lib.instance.deleteCurrentInstance(token, {
        purge,
        challengeIds,
      }),
    !session.token ? undefined : [session.token, form.purge!!, []],
  );

  remove.onSuccess = onDeleted;
  remove.onFail = (fail, t, p) => {
    switch (fail.case) {
      case HttpStatusCode.Accepted:
        mfa.onChallengeRequired(
          fail.body,
          remove.lambda((ids: string[]) => [t, p, ids]),
        );
        return i18n.str`Second factor authentication required.`;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unaouthorized.`;
      case HttpStatusCode.NotFound:
        return i18n.str`Not found.`;
      case HttpStatusCode.Conflict:
        return i18n.str`Conflict.`;
    }
  };
  if (mfa.pendingChallenge && mfa.repeatCall) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        onCompleted={mfa.repeatCall}
        onCancel={mfa.doCancelChallenge}
      />
    );
  }

  return (
    <div>
      <LocalNotificationBannerBulma notification={notification} />
      <section class="section">
        <section class="hero is-hero-bar">
          <div class="hero-body">
            <div class="level">
              <div class="level-left">
                <div class="level-item">
                  <span class="is-size-4">{text}</span>
                </div>
              </div>
            </div>
          </div>
        </section>
        <hr />

        <div class="columns">
          <div class="column" />
          <div class="column is-four-fifths">
            <FormProvider errors={errors} object={form} valueHandler={setValue}>
              <Input<State>
                name="name"
                label={i18n.str`Instance`}
                placeholder={instanceId}
                help={i18n.str`Write the instance name to confirm the deletion`}
              />
              <InputToggle<State>
                name="purge"
                label={i18n.str`Purge`}
                tooltip={i18n.str`All the data will be fully deleted, otherwise only the access will be removed.`}
              />
              <div class="buttons is-right mt-5">
                {onBack && (
                  <a class="button" onClick={onBack}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </a>
                )}

                <ButtonBetterBulma
                  class="button is-small is-danger"
                  type="submit"
                  data-tooltip={
                    hasErrors
                      ? i18n.str`Please complete the marked fields`
                      : i18n.str`Confirm operation`
                  }
                  onClick={remove}
                >
                  <i18n.Translate>DELETE</i18n.Translate>
                </ButtonBetterBulma>
              </div>
            </FormProvider>
          </div>
          <div class="column" />
        </div>
      </section>
    </div>
  );
}
