/*
 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 {
  AmountParseError,
  Amounts,
  AmountString,
  assertUnreachable,
  HttpStatusCode,
  InternationalizationAPI,
  PotDetailResponse,
  TalerMerchantApi,
  TranslatedString,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";
import { useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
} from "../../../../components/form/FormProvider.js";
import { Input } from "../../../../components/form/Input.js";
import { useSessionContext } from "../../../../context/session.js";
import { WithId } from "../../../../declaration.js";
import { InputArray } from "../../../../components/form/InputArray.js";
import { undefinedIfEmpty } from "../../../../utils/table.js";
import { Tooltip } from "../../../../components/Tooltip.js";

const TALER_SCREEN_ID = 39;

type Entity = TalerMerchantApi.PotModifyRequest;

interface Props {
  onUpdated: () => void;
  onBack?: () => void;
  moneyPot: PotDetailResponse & WithId;
}
export function UpdatePage({ moneyPot, onUpdated, onBack }: Props): VNode {
  const { i18n } = useTranslationContext();
  const {
    state: { token },
    lib,
  } = useSessionContext();
  const [state, setState] = useState<Partial<Entity>>({
    description: moneyPot.description,
    expected_pot_totals: moneyPot.pot_totals,
    new_pot_totals: moneyPot.pot_totals,
    pot_name: moneyPot.pot_name,
  });
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const data = state as TalerMerchantApi.PotModifyRequest;

  function isAmountValid(
    a: string,
    i18n: InternationalizationAPI,
  ): TranslatedString | undefined {
    const s = Amounts.parseWithError(a);
    if (s.type === "ok") return undefined;
    switch (s.case) {
      case AmountParseError.MISSING_CURRENCY:
        return i18n.str`Missing currency name`;
      case AmountParseError.BAD_CURRENCY:
        return i18n.str`Currency name must be only letters`;
      case AmountParseError.BAD_NUMBER:
        return i18n.str`Value can only by number`;
      case AmountParseError.TOO_HIGH:
        return i18n.str`The value is too high`;
      case AmountParseError.TOO_PRECISE:
        return i18n.str`The value is too precise`;
    }
  }

  let invalidAmount: TranslatedString | undefined = undefined;
  const errors = undefinedIfEmpty<FormErrors<Entity>>({
    pot_name: !state.pot_name ? i18n.str`Required` : undefined,
    new_pot_totals:
      !state.new_pot_totals || !state.new_pot_totals.length
        ? undefined
        : state.new_pot_totals.find((a) => {
              const res = isAmountValid(a, i18n);
              if (!res) return undefined;
              invalidAmount = i18n.str`Invalid amount "${a}": ${res}`;
              return res;
            }) !== undefined
          ? invalidAmount
          : undefined,
  });

  const update = safeFunctionHandler(
    i18n.str`update money pot`,
    lib.instance.updateMoneyPot.bind(lib.instance),
    !token || errors ? undefined : [token, moneyPot.id, data],
  );
  update.onSuccess = onUpdated;
  update.onFail = (fail) => {
    switch (fail.case) {
      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);
    }
  };

  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>Id:</i18n.Translate>
                    &nbsp;
                    <b>{moneyPot.id}</b>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </section>
        <hr />

        <section class="section is-main-section">
          <div class="columns">
            <div class="column is-four-fifths">
              <FormProvider
                object={state}
                errors={errors}
                valueHandler={setState}
              >
                <Input<Entity>
                  name="pot_name"
                  label={i18n.str`Name`}
                  // tooltip={i18n.str`Name of the category`}
                />
                <Input<Entity>
                  name="description"
                  label={i18n.str`Descripton`}
                  // tooltip={i18n.str`Name of the category`}
                />
                <InputArray<Entity>
                  name="new_pot_totals"
                  label={i18n.str`Totals`}
                  // placeholder={placeholder}
                  // help={help}
                  // tooltip={tooltip}
                  // toStr={(v?: string) =>
                  //   !v ? "" : v.replace(PAYTO_START_REGEX, "")
                  // }
                  // fromStr={(v: string) => `payto://${v}`}
                  unique
                />
              </FormProvider>

              <div class="buttons is-right mt-5">
                {onBack && (
                  <button class="button" onClick={onBack}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </button>
                )}
                <Tooltip text={i18n.str`Confirm operation`}>
                  <ButtonBetterBulma type="button" onClick={update}>
                    <i18n.Translate>Confirm</i18n.Translate>
                  </ButtonBetterBulma>
                </Tooltip>
              </div>
            </div>
          </div>
        </section>
      </section>
    </div>
  );
}
