/*
 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,
  assertUnreachable,
  HttpStatusCode,
  TalerMerchantApi,
  TalerMerchantInstanceHttpClient,
  TanChannel,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  useChallengeHandler,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { h, VNode } from "preact";
import { useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
  TalerForm,
} from "../../../components/form/FormProvider.js";
import { DefaultInstanceFormFields } from "../../../components/instance/DefaultInstanceFormFields.js";
import { SolveMFAChallenges } from "../../../components/SolveMFA.js";
import { useSessionContext } from "../../../context/session.js";
import { undefinedIfEmpty } from "../../../utils/table.js";
import { CopyButton } from "../../../components/modal/index.js";
import { Tooltip } from "../../../components/Tooltip.js";
import { maybeTryFirstMFA } from "../accounts/create/CreatePage.js";
import {
  EMAIL_REGEX,
  PHONE_JUST_NUMBERS_REGEX,
} from "../../../utils/constants.js";

const TALER_SCREEN_ID = 75;

export type Entity = TalerMerchantApi.InstanceReconfigurationMessage &
  TalerForm;

export interface Props {
  doUpdate: typeof TalerMerchantInstanceHttpClient.prototype.updateCurrentInstance;
  onConfirm: () => void;
  selected: TalerMerchantApi.QueryInstancesResponse;
  isLoading: boolean;
  onBack: () => void;
}

function convert(from: TalerMerchantApi.QueryInstancesResponse): Entity {
  const {
    default_pay_delay,
    default_wire_transfer_delay,
    default_refund_delay,
    ...rest
  } = from;

  const defaults: Partial<Entity> = {
    use_stefan: false,
    default_pay_delay: default_pay_delay,
    default_refund_delay: default_refund_delay,
    default_wire_transfer_delay: default_wire_transfer_delay,
  };
  return { ...defaults, ...rest } as Entity;
}

export function UpdatePage({
  doUpdate,
  onConfirm,
  selected,
  onBack,
}: Props): VNode {
  const { state, config, lib } = useSessionContext();

  const [value, valueHandler] = useState<Partial<Entity>>(convert(selected));

  const { i18n } = useTranslationContext();

  const serverRequiresEmail =
    config.mandatory_tan_channels?.indexOf(TanChannel.EMAIL) !== -1;
  const serverRequiresSms =
    config.mandatory_tan_channels?.indexOf(TanChannel.SMS) !== -1;

  let phoneRegex: RegExp | undefined = undefined;
  if (config.phone_regex) {
    try {
      phoneRegex = new RegExp(config.phone_regex);
    } catch (e) {
      console.log("invalid phone regex", e);
    }
  }

  const errors = undefinedIfEmpty<FormErrors<Entity>>({
    name: !value.name ? i18n.str`Required` : undefined,
    email: !value.email
      ? undefined
      : !EMAIL_REGEX.test(value.email)
        ? i18n.str`Doesn't have the pattern of an email`
        : undefined,
    phone_number: !value.phone_number
      ? undefined
      : !phoneRegex
        ? !value.phone_number.startsWith("+")
          ? i18n.str`Should start with +`
          : !PHONE_JUST_NUMBERS_REGEX.test(value.phone_number)
            ? i18n.str`A phone number consists of numbers only`
            : undefined
        : !phoneRegex.test(value.phone_number)
          ? i18n.str`Invalid phone number`
          : undefined,
    default_pay_delay: !value.default_pay_delay
      ? i18n.str`Required`
      : value.default_pay_delay.d_us === "forever"
        ? i18n.str`Invalid value`
        : undefined,
    default_refund_delay: !value.default_refund_delay
      ? i18n.str`Required`
      : value.default_refund_delay.d_us === "forever"
        ? i18n.str`Invalid value`
        : undefined,
    default_wire_transfer_delay: !value.default_wire_transfer_delay
      ? i18n.str`Required`
      : value.default_wire_transfer_delay.d_us === "forever"
        ? i18n.str`Invalid value`
        : undefined,
    address: undefinedIfEmpty({
      address_lines:
        value.address?.address_lines && value.address?.address_lines.length > 7
          ? i18n.str`Max 7 lines`
          : undefined,
    }),
    jurisdiction: undefinedIfEmpty({
      address_lines:
        value.address?.address_lines && value.address?.address_lines.length > 7
          ? i18n.str`Max 7 lines`
          : undefined,
    }),
  });

  const hasErrors = errors !== undefined;

  const {
    default_pay_delay,
    default_wire_transfer_delay,
    default_refund_delay,
    ...rest
  } = value as Required<Entity>;
  const result: TalerMerchantApi.InstanceReconfigurationMessage = {
    default_pay_delay: !default_pay_delay ? undefined : default_pay_delay,
    default_refund_delay: !default_refund_delay
      ? undefined
      : default_refund_delay,
    default_wire_transfer_delay: !default_wire_transfer_delay
      ? undefined
      : default_wire_transfer_delay,
    ...rest,
  };
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const mfa = useChallengeHandler();
  const update = safeFunctionHandler(
    i18n.str`update instance settings`,
    async (
      token: AccessToken,
      d: TalerMerchantApi.InstanceReconfigurationMessage,
      challengeIds: string[],
    ) => {
      const resp = await doUpdate(token, d, { challengeIds });
      if (resp.type === "fail" && resp.case === HttpStatusCode.Accepted) {
        await maybeTryFirstMFA(lib.instance, mfa, resp.body);
      }
      return resp;
    },
    hasErrors || !state.token ? undefined : [state.token, result, []],
  );
  update.onSuccess = onConfirm;
  update.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Accepted:
        return undefined;
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized.`;
      case HttpStatusCode.NotFound:
        return i18n.str`Instance not found.`;
      default:
        assertUnreachable(fail);
    }
  };
  const retry = update.lambda((challengesIds: string[]) => [
    update.args![0],
    update.args![1],
    challengesIds,
  ]);

  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        initial={mfa.initial}
        focus
        onCompleted={retry}
        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">
                    <i18n.Translate>Instance id</i18n.Translate>:{" "}
                    <b>{state.instance}</b>
                  </span>
                </div>
              </div>
            </div>
            <div class="level">
              <div class="level-left">
                <div class="level-item">
                  <span class="is-size-6">
                    <i18n.Translate>URL</i18n.Translate>:{" "}
                    <b>{lib.instance.baseUrl}</b>
                  </span>
                  <div style={{ marginLeft: 10 }}>
                    <CopyButton getContent={() => lib.instance.baseUrl} />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <hr />

        <div class="columns">
          <div class="column" />
          <div class="column is-four-fifths">
            <FormProvider<Entity>
              errors={errors}
              object={value}
              valueHandler={valueHandler}
            >
              <DefaultInstanceFormFields
                showId={false}
                setDefaultPayDelay={() => {
                  valueHandler((v) => ({
                    ...v,
                    default_pay_delay: config.default_pay_delay,
                  }));
                }}
                setDefaultRefundDelay={() => {
                  valueHandler((v) => ({
                    ...v,
                    default_refund_delay: config.default_refund_delay,
                  }));
                }}
                setDefaultWireDelay={() => {
                  valueHandler((v) => ({
                    ...v,
                    default_wire_transfer_delay:
                      config.default_wire_transfer_delay,
                  }));
                }}
              />

              <div class="buttons is-right mt-4">
                <Tooltip text={i18n.str`Cancel operation`}>
                  <button type="button" class="button" onClick={onBack}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </button>
                </Tooltip>

                <Tooltip
                  text={
                    hasErrors
                      ? i18n.str`Please complete the marked fields`
                      : i18n.str`Confirm operation`
                  }
                >
                  <ButtonBetterBulma type="submit" onClick={update}>
                    <i18n.Translate>Confirm</i18n.Translate>
                  </ButtonBetterBulma>
                </Tooltip>
              </div>
            </FormProvider>
          </div>
          <div class="column" />
        </div>
      </section>
    </div>
  );
}
