/*
 This file is part of GNU Taler
 (C) 2022-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/>
 */
import {
  FormMetadata,
  FormUI,
  LocalNotificationBanner,
  preloadedForms,
  UIHandlerId,
  useFormMeta,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";

type FormType = {
  form: string;
};

type Props = {
  formId?: string;
};

export function TriggerForms({ formId }: Props): VNode {
  const { i18n } = useTranslationContext();
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();

  const pf = preloadedForms(i18n);

  const theForm: FormMetadata = {
    id: "asd",
    version: 1,
    label: i18n.str`Trigger KYC balance`,
    config: {
      type: "single-column",
      fields: [
        {
          id: "form" as UIHandlerId,
          type: "selectOne",
          label: i18n.str`Form`,
          help: i18n.str`You can also use the formId in the UR after "/test/show-forms/$FORM_ID"`,
          required: true,
          choices: pf.map((form) => {
            return {
              label: `${form.id}: ${form.label}`,
              value: form.id,
            };
          }),
        },
      ],
    },
  };

  const {
    model: handler,
    status,
    design,
  } = useFormMeta<FormType>(
    theForm,
    {},
    {
      form: formId,
    },
  );

  const selected = !status.result?.form
    ? undefined
    : pf.find((f) => f.id === status.result.form);
  return (
    <div class="rounded-lg bg-white px-5 py-6 shadow m-4">
      <LocalNotificationBanner notification={notification} />
      <div class="space-y-10 divide-y -mt-5 divide-gray-900/10">
        <FormUI model={handler} design={design} />
      </div>
      {!selected ? undefined : <ShowForm form={selected} />}
    </div>
  );
}

function ShowForm({ form }: { form: FormMetadata }) {
  const { model: handler, design } = useFormMeta<FormType>(form, {}, {});

  return (
    <Fragment>
      <div class="space-y-10 divide-y -mt-5 divide-gray-900/10">
        <FormUI model={handler} design={design} />
      </div>
    </Fragment>
  );
}
