/*
 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,
  ChallengeResponse,
  HttpStatusCode,
} from "@gnu-taler/taler-util";
import {
  useChallengeHandler,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";
import { useState } from "preact/hooks";
import { AsyncButton } from "../../../components/exception/AsyncButton.js";
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";
import { Notification } from "../../../utils/types.js";

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 [notif, setNotif] = useState<Notification | undefined>(undefined);

  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 mfa = useChallengeHandler();
  const [doDelete, repeatDelete] = mfa.withMfaHandler(
    ({ challengeIds, onChallengeRequired }) =>
      async function doDeleteImpl() {
        if (hasErrors) return;
        try {
          const resp = await lib.instance.deleteCurrentInstance(session.token, {
            purge: form.purge,
            challengeIds,
          });
          if (resp.type === "ok") {
            logOut();
            return onDeleted();
          }
          switch (resp.case) {
            case HttpStatusCode.Accepted: {
              onChallengeRequired(resp.body);
              return;
            }
            case HttpStatusCode.Unauthorized: {
              setNotif({
                message: i18n.str`Failed to delete the instance`,
                type: "ERROR",
                description: resp.detail?.hint,
              });
              return;
            }
            case HttpStatusCode.NotFound: {
              setNotif({
                message: i18n.str`Failed to delete the instance`,
                type: "ERROR",
                description: resp.detail?.hint,
              });
              return;
            }
            case HttpStatusCode.Conflict: {
              setNotif({
                message: i18n.str`Failed to delete the instance`,
                type: "ERROR",
                description: resp.detail?.hint,
              });
              return;
            }
            default: {
              assertUnreachable(resp);
            }
          }
        } catch (error) {
          setNotif({
            message: i18n.str`Failed to delete the instance.`,
            type: "ERROR",
            description: error instanceof Error ? error.message : undefined,
          });
        }
      },
  );
  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        onCompleted={repeatDelete}
        onCancel={mfa.doCancelChallenge}
      />
    );
  }

  return (
    <div>
      <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>
                )}

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