/*
 This file is part of GNU Taler
 (C) 2022-2025 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/>
 */
import { PaytoString } from "@gnu-taler/taler-util";
import {
  FormDesign,
  FormUI,
  InternationalizationAPI,
  onComponentUnload,
  useForm,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { h, VNode } from "preact";
import { useCurrentDecisionRequest } from "../../hooks/decision-request.js";

const TALER_SCREEN_ID = 106;

/**
 * Mark for further investigation and explain decision
 * @param param0
 * @returns
 */
export function Justification({ newPayto }: { newPayto?: string }): VNode {
  const isNewAccount = !!newPayto;

  const { i18n } = useTranslationContext();
  const [request, updateRequest] = useCurrentDecisionRequest();
  const design = formDesign(i18n, isNewAccount);

  const form = useForm<FormType>(design, {
    investigate:
      request.keep_investigating ?? request.original?.to_investigate ?? false,
    justification: request.justification,
    accountName: request.accountName,
  });

  onComponentUnload(() => {
    updateRequest("unload justification", {
      keep_investigating: !!form.status.result.investigate,
      justification: form.status.result.justification ?? "",
      accountName: form.status.result.accountName ?? "",
    });
  });

  return (
    <div>
      <FormUI design={design} model={form.model} />
    </div>
  );
}

type FormType = {
  justification: string;
  accountName: string;
  investigate: boolean;
  measure: string;
};

const formDesign = (
  i18n: InternationalizationAPI,
  unknownAccount: boolean,
): FormDesign => ({
  type: "single-column",
  fields: [
    {
      id: "justification",
      type: "textArea",
      required: true,
      label: i18n.str`Justification`,
    },
    {
      id: "investigate",
      type: "toggle",
      label: i18n.str`Keep investigation?`,
    },
    {
      id: "accountName",
      type: "text",
      label: i18n.str`Account holder`,
      required: true,
      help: i18n.str`Full name of the account holder`,
      hidden: !unknownAccount,
    },
  ],
});
