/*
 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,
  Paytos,
  Result,
  TalerMerchantApi,
  TalerMerchantManagementHttpClient,
  assertUnreachable,
  opEmptySuccess,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  MfaState,
  SafeHandlerTemplate,
  useChallengeHandler,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
  TalerForm,
} from "../../../../components/form/FormProvider.js";
import { Input } from "../../../../components/form/Input.js";
import { InputPassword } from "../../../../components/form/InputPassword.js";
import { InputPaytoForm } from "../../../../components/form/InputPaytoForm.js";
import { InputSelector } from "../../../../components/form/InputSelector.js";
import { InputToggle } from "../../../../components/form/InputToggle.js";
import { FragmentPersonaFlag } from "../../../../components/menu/SideBar.js";
import { CompareAccountsModal } from "../../../../components/modal/index.js";
import { SolveMFAChallenges } from "../../../../components/SolveMFA.js";
import { Tooltip } from "../../../../components/Tooltip.js";
import { useSessionContext } from "../../../../context/session.js";
import { UIElement, usePreference } from "../../../../hooks/preference.js";
import { undefinedIfEmpty } from "../../../../utils/table.js";
import { safeConvertURL } from "../update/UpdatePage.js";
import { TestRevenueErrorType, testRevenueAPI } from "./index.js";

const TALER_SCREEN_ID = 33;

type Entity = TalerMerchantApi.AccountAddDetails & {
  verified?: boolean;
} & TalerForm;

interface Props {
  onCreated: () => void;
  onBack?: () => void;
}

const SUBJECT_METADATA_REGEX = /^[a-zA-Z0-9-.:]{1,40}$/;

export function CreatePage({ onCreated, onBack }: Props): VNode {
  const { i18n } = useTranslationContext();

  const [{ persona }] = usePreference();
  const accountAuthType =
    persona === "tester" ? ["none", "basic", "bearer"] : ["none", "basic"];

  const [state, setState] = useState<Partial<Entity>>({
    credit_facade_credentials: {
      type: "basic",
      password: "",
      username: "",
    },
  });
  const facadeURL = safeConvertURL(state.credit_facade_url);

  const [revenuePayto, setRevenuePayto] = useState<Paytos.URI | undefined>(
    undefined,
  );
  const parsed = !state.payto_uri
    ? Result.error(undefined)
    : Paytos.fromString(state.payto_uri);
  const safeParsed = Result.orUndefined(parsed);
  const errors = undefinedIfEmpty<FormErrors<Entity>>({
    payto_uri: !state.payto_uri ? i18n.str`Required` : undefined,
    extra_wire_subject_metadata: !state.extra_wire_subject_metadata
      ? undefined
      : !SUBJECT_METADATA_REGEX.test(state.extra_wire_subject_metadata)
        ? i18n.str`The extra data should be between 1 and 40 characters of letters, numbers, dot, dash and colon.`
        : undefined,

    credit_facade_credentials: undefinedIfEmpty(
      !state.credit_facade_credentials || !state.credit_facade_url
        ? undefined
        : {
          username:
            state.credit_facade_credentials.type === "basic" &&
              !state.credit_facade_credentials.username
              ? i18n.str`Required`
              : undefined,
          password:
            state.credit_facade_credentials.type === "basic" &&
              !state.credit_facade_credentials.password
              ? i18n.str`Required`
              : undefined,
        },
    ) as any,
    credit_facade_url: !state.credit_facade_url
      ? undefined
      : !facadeURL
        ? i18n.str`Invalid url`
        : !facadeURL.href.endsWith("/")
          ? i18n.str`URL must end with a '/'`
          : facadeURL.searchParams.size > 0
            ? i18n.str`URL must not contain params`
            : facadeURL.hash
              ? i18n.str`URL must not hash param`
              : undefined,
  });

  const hasErrors = errors !== undefined;

  const credit_facade_url = !state.credit_facade_url
    ? undefined
    : facadeURL?.href;
  const credit_facade_credentials:
    | TalerMerchantApi.FacadeCredentials
    | undefined =
    credit_facade_url == undefined
      ? undefined
      : state.credit_facade_credentials?.type === "basic"
        ? {
          type: "basic",
          password: state.credit_facade_credentials.password,
          username: state.credit_facade_credentials.username,
        }
        : {
          type: "none",
        };
  const { state: session, lib } = useSessionContext();

  const request: TalerMerchantApi.AccountAddDetails | undefined =
    !state.payto_uri
      ? undefined
      : {
        payto_uri: state.payto_uri,
        credit_facade_credentials,
        credit_facade_url,
        extra_wire_subject_metadata: state.extra_wire_subject_metadata,
      };

  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const mfa = useChallengeHandler();
  const add = safeFunctionHandler(
    i18n.str`add bank account`,
    async (token: AccessToken, request: Entity, challengeIds: string[]) => {
      const resp = await lib.instance.addBankAccount(token, request, { challengeIds })
      if (resp.type === "fail" && resp.case === HttpStatusCode.Accepted) {
        await maybeTryFirstMFA(lib.instance, mfa, resp.body);
      }
      return resp
    },
    !session.token || !request ? undefined : [session.token, request, []],
  );
  add.onSuccess = onCreated;
  add.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Accepted:
        return undefined;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized.`;
      case HttpStatusCode.NotFound:
        return i18n.str`Not found.`;
      case HttpStatusCode.Conflict:
        return i18n.str`Conflict.`;
      default:
        assertUnreachable(fail);
    }
  };

  const repeat = add.lambda((ids: string[]) => [
    add.args![0],
    add.args![1],
    ids,
  ]);

  const revenueAPI = !state.credit_facade_url
    ? undefined
    : new URL("./", state.credit_facade_url);

  const test = safeFunctionHandler(
    i18n.str`test revenue api`,
    testRevenueAPI,
    !state.credit_facade_credentials || !revenueAPI
      ? undefined
      : [revenueAPI, state.credit_facade_credentials],
  );

  test.onSuccess = (success) => {
    const match = state.payto_uri === Paytos.toFullString(success);
    setState({
      ...state,
      verified: match,
    });
    if (!match) {
      setRevenuePayto(success);
    }
  };

  test.onFail = (fail) => {
    switch (fail.case) {
      case TestRevenueErrorType.CANT_VALIDATE:
        return i18n.str`The request was made correctly, but the bank's server did not respond with the appropriate value for 'credit_account', so we cannot confirm that it is the same bank account.`;
      case HttpStatusCode.BadRequest:
        return i18n.str`Server didn't like the request we made.`;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized, check credentials.`;
      case HttpStatusCode.NotFound:
        return i18n.str`The endpoint does not seem to be a Taler Revenue API.`;
      case TestRevenueErrorType.BAD_PAYTO:
        return i18n.str`Unsupported type of account`;
      default:
        assertUnreachable(fail);
    }
  };

  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        initial={mfa.initial}
        focus
        onCompleted={repeat}
        onCancel={mfa.doCancelChallenge}
      />
    );
  }
  return (
    <Fragment>
      <LocalNotificationBannerBulma notification={notification} />
      <section class="section is-main-section">
        <div class="columns">
          <div class="column" />
          <div class="column is-four-fifths">
            <FormProvider
              object={state}
              valueHandler={setState}
              errors={errors}
            >
              <InputPaytoForm<Entity>
                name="payto_uri"
                label={i18n.str`Account details`}
              />
              <FragmentPersonaFlag point={UIElement.option_exraWireSubject}>
                <Input<Entity>
                  name="extra_wire_subject_metadata"
                  label={i18n.str`Extra subject`}
                  expand
                  tooltip={i18n.str`Additional text to include in the wire transfer subject when settling the payment`}
                />
              </FragmentPersonaFlag>
              <FragmentPersonaFlag point={UIElement.action_useRevenueApi}>
                <div class="message-body" style={{ marginBottom: 10 }}>
                  <p>
                    <i18n.Translate>
                      If the bank supports Taler Revenue API then you can add
                      the endpoint URL below to keep the revenue information in
                      sync.
                    </i18n.Translate>
                  </p>
                </div>
                <Input<Entity>
                  name="credit_facade_url"
                  label={i18n.str`Endpoint URL`}
                  help="https://bank.demo.taler.net/accounts/${USERNAME}/taler-revenue/"
                  expand
                  tooltip={i18n.str`From where the merchant can download information about incoming wire transfers to this account`}
                  inputType="url"
                />
                <InputSelector
                  name="credit_facade_credentials.type"
                  label={i18n.str`Auth type`}
                  tooltip={i18n.str`Choose the authentication type for the account info URL`}
                  values={accountAuthType}
                  toStr={(str) => {
                    if (str === "none") return i18n.str`Without authentication`;
                    if (str === "bearer") return i18n.str`With token`;
                    return i18n.str`With username and password`;
                  }}
                />
                {state.credit_facade_credentials?.type === "basic" ? (
                  <Fragment>
                    <Input
                      name="credit_facade_credentials.username"
                      label={i18n.str`Username`}
                      tooltip={i18n.str`Username to access the account information.`}
                      autoComplete="username"
                    />
                    <InputPassword
                      name="credit_facade_credentials.password"
                      expand
                      label={i18n.str`Password`}
                      tooltip={i18n.str`Password to access the account information.`}
                      autoComplete="current-password"
                    />
                  </Fragment>
                ) : undefined}
                {state.credit_facade_credentials?.type === "bearer" ? (
                  <Fragment>
                    <Input
                      name="credit_facade_credentials.token"
                      label={i18n.str`Token`}
                      inputType="password"
                      tooltip={i18n.str`Access token to access the account information.`}
                    />
                  </Fragment>
                ) : undefined}
                <InputToggle<Entity>
                  label={i18n.str`Match`}
                  tooltip={i18n.str`Check if the information matches the server info.`}
                  name="verified"
                  readonly
                  threeState
                  side={
                    <Tooltip text={i18n.str`Verify details with server`}>
                      <ButtonBetterBulma
                        class="button is-info"
                        type="button"
                        onClick={test}
                      >
                        <i18n.Translate>Test</i18n.Translate>
                      </ButtonBetterBulma>
                    </Tooltip>
                  }
                />
              </FragmentPersonaFlag>
              <div class="buttons is-right mt-5">
                {onBack && (
                  <button class="button" onClick={onBack}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </button>
                )}
                <Tooltip
                  text={
                    hasErrors
                      ? i18n.str`Please complete the marked fields`
                      : i18n.str`Confirm operation`
                  }
                >
                  <ButtonBetterBulma onClick={add} type="submit">
                    <i18n.Translate>Confirm</i18n.Translate>
                  </ButtonBetterBulma>
                </Tooltip>
              </div>
            </FormProvider>
          </div>
          <div class="column" />
        </div>
      </section>
      {!revenuePayto ? undefined : (
        <CompareAccountsModal
          onCancel={() => {
            setRevenuePayto(undefined);
          }}
          confirm={safeFunctionHandler(
            i18n.str`parse revenue payto`,
            async () => {
              setState({
                ...state,
                payto_uri: Paytos.toFullString(revenuePayto),
              });
              setRevenuePayto(undefined);
              return opEmptySuccess();
            },
            [],
          )}
          formPayto={safeParsed}
          testPayto={revenuePayto}
        />
      )}
    </Fragment>
  );
}

export async function maybeTryFirstMFA(
  api: TalerMerchantManagementHttpClient,
  mfa: MfaState,
  b: TalerMerchantApi.ChallengeResponse,
  repeat?: SafeHandlerTemplate<[ids: string[]], any>,
) {
  const letUserDecide = b.combi_and === false && b.challenges.length > 1
  if (b.challenges.length === 0 || letUserDecide) {
    mfa.onChallengeRequired(b, repeat);
    return;
  }
  const challenge = b.challenges[0];
  const result = await api.sendChallenge(challenge.challenge_id);
  if (result.type === "fail") {
    mfa.onChallengeRequired(b, repeat);
  } else {
    mfa.onChallengeRequiredWithInitial(b, {
      request: challenge,
      response: result.body,
    }, repeat);
  }
}
