/*
 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 {
  AmountString,
  assertUnreachable,
  HttpStatusCode,
  TalerErrorCode,
  TalerMerchantApi,
  UsingTemplateDetails,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  undefinedIfEmpty,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { VNode, h } from "preact";
import { useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
} from "../../../../components/form/FormProvider.js";
import { Input } from "../../../../components/form/Input.js";
import { InputWithAddon } from "../../../../components/form/InputWithAddon.js";
import { useSessionContext } from "../../../../context/session.js";
import { Tooltip } from "../../../../components/Tooltip.js";

const TALER_SCREEN_ID = 66;

type Entity = TalerMerchantApi.TemplateContractDetails;

interface Props {
  id: string;
  template: TalerMerchantApi.TemplateDetails;
  onOrderCreated: (orderId: string) => void;
  onBack?: () => void;
}

export function UsePage({
  id,
  template,
  onBack,
  onOrderCreated,
}: Props): VNode {
  const { i18n } = useTranslationContext();
  const { lib } = useSessionContext();
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();

  const [state, setState] = useState<Partial<Entity>>({
    currency:
      template.editable_defaults?.currency ??
      template.template_contract.currency,
    // FIXME: Add additional check here, editable default might be a plain string!
    amount: (template.editable_defaults?.amount ??
      template.template_contract.amount) as AmountString,
    summary:
      template.editable_defaults?.summary ?? template.template_contract.summary,
  });

  const errors = undefinedIfEmpty<FormErrors<Entity>>({
    amount: !state.amount ? i18n.str`An amount is required` : undefined,
    summary: !state.summary
      ? i18n.str`An order summary is required`
      : undefined,
  });

  /**
   * If the template already has fields then do not send those.
   */
  const details: UsingTemplateDetails = {
    amount: template.template_contract.amount ? undefined : state.amount,
    summary: template.template_contract.summary ? undefined : state.summary,
  };
  const useTemplate = safeFunctionHandler(
    i18n.str`create order from template`,
    lib.instance.useTemplateCreateOrder.bind(lib.instance),
    !!errors ? undefined : [id, details],
  );
  useTemplate.onSuccess = (success) => {
    onOrderCreated(success.order_id);
  };
  useTemplate.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized.`;
      case TalerErrorCode.MERCHANT_PRIVATE_POST_ORDERS_INSTANCE_CONFIGURATION_LACKS_WIRE:
        return i18n.str`No active bank accounts configured. At least one bank account must be available to create new orders`;
      case HttpStatusCode.Conflict:
        return i18n.str`Conflict.`;
      case HttpStatusCode.Gone:
        return i18n.str`No more stock for product with ID "${fail.body.product_id}".`;
      case HttpStatusCode.UnavailableForLegalReasons:
        return i18n.str`No exchange would accept a payment because of KYC requirements.`;
      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>New order from template</i18n.Translate>:{" "}
                    <b>{id}</b>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </section>
      </section>
      <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}
            >
              <InputWithAddon<Entity>
                name="amount"
                label={i18n.str`Amount`}
                addonBefore={state.currency}
                inputType="decimal"
                toStr={(v?: AmountString) => v?.split(":")[1] || ""}
                fromStr={(v: string) =>
                  !v ? undefined : `${state.currency}:${v}`
                }
                inputExtra={{ min: 0, step: 0.001 }}
                tooltip={i18n.str`Amount of the order`}
                readonly={!!template.template_contract.amount}
              />

              <Input<Entity>
                name="summary"
                inputType="multiline"
                label={i18n.str`Order summary`}
                readonly={!!template.template_contract.summary}
                tooltip={i18n.str`Title of the order to be shown to the customer`}
              />
              <div class="buttons is-right mt-5">
                {onBack && (
                  <button type="button" class="button" onClick={onBack}>
                    <i18n.Translate>Cancel</i18n.Translate>
                  </button>
                )}
                <Tooltip
                  text={
                    errors !== undefined
                      ? i18n.str`Please complete the marked fields`
                      : i18n.str`Confirm operation`
                  }
                >
                  <ButtonBetterBulma type="submit" onClick={useTemplate}>
                    <i18n.Translate>Confirm</i18n.Translate>
                  </ButtonBetterBulma>
                </Tooltip>
              </div>
            </FormProvider>
          </div>
          <div class="column" />
        </div>
      </section>
    </div>
  );
}
