/*
 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,
  TalerMerchantApi,
} from "@gnu-taler/taler-util";
import {
  LocalNotificationBannerBulma,
  SafeHandlerTemplate,
  useChallengeHandler,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { h, VNode } from "preact";
import { useState } from "preact/hooks";
import { CardTable as CardTableActive } from "./TableActive.js";
import { Fragment } from "preact";
import { SolveMFAChallenges } from "../../../components/SolveMFA.js";
import { useSessionContext } from "../../../context/session.js";
import { ConfirmModal } from "../../../components/modal/index.js";

const TALER_SCREEN_ID = 28;

interface Props {
  instances: TalerMerchantApi.Instance[];
  onCreate: () => void;
  onUpdate: (id: string) => void;
  onChangePassword: (id: string) => void;
  selected?: boolean;
}

export function View({
  instances,
  onCreate,
  onUpdate,
  onChangePassword,
  selected,
}: Props): VNode {
  const [show, setShow] = useState<"active" | "deleted" | null>("active");
  const showIsActive = show === "active" ? "is-active" : "";
  const showIsDeleted = show === "deleted" ? "is-active" : "";
  const showAll = show === null ? "is-active" : "";
  const { i18n } = useTranslationContext();

  const showingInstances = showIsDeleted
    ? instances.filter((i) => i.deleted)
    : showIsActive
      ? instances.filter((i) => !i.deleted)
      : instances;

  const { state: session, lib } = useSessionContext();

  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const mfa = useChallengeHandler();
  const deleteAction = safeFunctionHandler(
    (
      token: AccessToken,
      instance: TalerMerchantApi.Instance,
      purge: boolean,
      challengeIds: string[],
    ) =>
      lib.instance.deleteInstance(token, instance.id, { challengeIds, purge }),
  );

  const [deleting, setDeleting] = useState<TalerMerchantApi.Instance>();
  const [purging, setPurging] = useState<boolean>();

  deleteAction.onSuccess = (_, t, instance) => {
    setDeleting(undefined);
    return i18n.str`Instance "${instance.name}" (ID: ${instance.id}) has been deleted.`;
  };

  deleteAction.onFail = (fail, t, i, p) => {
    switch (fail.case) {
      case HttpStatusCode.Accepted:
        mfa.onChallengeRequired(
          fail.body,
          deleteAction.lambda((ids: string[]) => [t, i, p, ids]),
        );
        return i18n.str`Second factor authentication required.`;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized.`;
      case HttpStatusCode.NotFound:
        return i18n.str`Not found.`;
      case HttpStatusCode.Conflict:
        return i18n.str`Conflict.`;
    }
  };

  const remove =
    !session.token || !deleting
      ? deleteAction
      : deleteAction.withArgs(session.token, deleting, false, []);
  const purge =
    !session.token || !deleting
      ? deleteAction
      : deleteAction.withArgs(session.token, deleting, true, []);

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

  return (
    <Fragment>
      <LocalNotificationBannerBulma notification={notification} />
      {deleting &&
        (purging ? (
          <PurgeModal
            element={deleting}
            onCancel={() => setDeleting(undefined)}
            confirm={purge}
          />
        ) : (
          <DeleteModal
            element={deleting}
            onCancel={() => setDeleting(undefined)}
            confirm={remove}
          />
        ))}
      <section class="section is-main-section">
        <div class="columns">
          <div class="column is-two-thirds">
            <div class="tabs" style={{ overflow: "inherit" }}>
              <ul>
                <li class={showIsActive}>
                  <div
                    class="has-tooltip-right"
                    data-tooltip={i18n.str`Only show active instances`}
                  >
                    <a onClick={() => setShow("active")}>
                      <i18n.Translate>Active</i18n.Translate>
                    </a>
                  </div>
                </li>
                <li class={showIsDeleted}>
                  <div
                    class="has-tooltip-right"
                    data-tooltip={i18n.str`Only show deleted instances`}
                  >
                    <a onClick={() => setShow("deleted")}>
                      <i18n.Translate>Deleted</i18n.Translate>
                    </a>
                  </div>
                </li>
                <li class={showAll}>
                  <div
                    class="has-tooltip-right"
                    data-tooltip={i18n.str`Show all instances`}
                  >
                    <a onClick={() => setShow(null)}>
                      <i18n.Translate>All</i18n.Translate>
                    </a>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <CardTableActive
          instances={showingInstances}
          onDelete={(d) => {
            setDeleting(d)
            setPurging(false)
          }}
          onPurge={(d) => {
            setDeleting(d)
            setPurging(true)
          }}
          onChangePassword={onChangePassword}
          onUpdate={onUpdate}
          selected={selected}
          onCreate={onCreate}
        />
      </section>
    </Fragment>
  );
}

interface DeleteModalProps {
  element: { id: string; name: string };
  onCancel: () => void;
  confirm: SafeHandlerTemplate<any, any>;
}

export function DeleteModal({
  element,
  onCancel,
  confirm,
}: DeleteModalProps): VNode {
  const { i18n } = useTranslationContext();
  return (
    <ConfirmModal
      label={`Delete instance`}
      description={`Delete the instance "${element.name}"`}
      danger
      active
      onCancel={onCancel}
      confirm={confirm}
    >
      <p>
        <i18n.Translate>
          If you delete the instance named <b>&quot;{element.name}&quot;</b>{" "}
          (ID: <b>{element.id}</b>), the merchant will no longer be able to
          process orders and refunds
        </i18n.Translate>
      </p>
      <p>
        <i18n.Translate>
          This action deletes the instance's private key, but preserves all
          transaction data. You can still access the transaction data after
          having deleted the instance.
        </i18n.Translate>
      </p>
      <p class="warning">
        <i18n.Translate>
          Deleting an instance{" "}
          <b>
            <i18n.Translate>This cannot be undone!</i18n.Translate>
          </b>
        </i18n.Translate>
      </p>
    </ConfirmModal>
  );
}

function PurgeModal({ element, onCancel, confirm }: DeleteModalProps): VNode {
  const { i18n } = useTranslationContext();
  return (
    <ConfirmModal
      label={`Purge the instance`}
      description={`Purge the instance "${element.name}"`}
      danger
      active
      onCancel={onCancel}
      confirm={confirm}
    >
      <p>
        <i18n.Translate>
          If you purge the instance named <b>&quot;{element.name}&quot;</b> (ID:{" "}
          <b>{element.id}</b>), you will also delete all of its transaction
          data!
        </i18n.Translate>
      </p>
      <p>
        <i18n.Translate>
          The instance will disappear from your list and you will no longer be
          able to access its data.
        </i18n.Translate>
      </p>
      <p class="warning">
        <i18n.Translate>
          Purging an instance{" "}
          <b>
            <i18n.Translate>This cannot be undone!</i18n.Translate>
          </b>
        </i18n.Translate>
      </p>
    </ConfirmModal>
  );
}
