/*
 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 {
  ButtonBetter,
  FormDesign,
  FormUI,
  InternationalizationAPI,
  LocalNotificationBanner,
  useForm,
  useLocalNotificationBetter,
  useTranslationContext
} from "@gnu-taler/web-util/browser";
import { VNode, h } from "preact";
import { OfficerNotFound } from "../hooks/officer.js";
import { usePreferences } from "../hooks/preferences.js";
import { HttpStatusCode, opKnownFailure } from "@gnu-taler/taler-util";

type FormType = {
  password: string;
  repeat: string;
};

const TALER_SCREEN_ID = 125;

const createAccountForm = (
  i18n: InternationalizationAPI,
  allowInsecurePassword: boolean,
): FormDesign => ({
  type: "single-column",
  fields: [
    {
      id: "password",
      type: "secret",
      label: i18n.str`Password`,
      required: true,
      validator(value) {
        return !value
          ? i18n.str`Required`
          : allowInsecurePassword
            ? undefined
            : value.length < 12
              ? i18n.str`should have at least 12 characters`
              : !value.match(/[a-z]/) && value.match(/[A-Z]/)
                ? i18n.str`should have lowercase and uppercase characters`
                : !value.match(/\d/)
                  ? i18n.str`should have numbers`
                  : !value.match(/[^a-zA-Z\d]/)
                    ? i18n.str`should have at least one character which is not a number or letter`
                    : undefined;
      },
    },
    {
      id: "repeat",
      type: "secret",
      label: i18n.str`Repeat password`,
      required: true,
      validator(value, state) {
        return !value
          ? i18n.str`Required`
          : state.password !== value
              ? i18n.str`doesn't match`
            : undefined;
      },
    },
  ],
});

export function CreateAccount({
  officer,
}: {
  officer: OfficerNotFound;
}): VNode {
  const { i18n } = useTranslationContext();
  const [settings] = usePreferences();
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();

  const design = createAccountForm(i18n, settings.allowInsecurePassword);

  const { model: handler, status } = useForm<FormType>(design, {
    password: undefined,
    repeat: undefined,
  });

  const create = safeFunctionHandler(
    officer.create,
    status.status === "fail" ? undefined : [status.result.password],
  );

  return (
    <div class="flex min-h-full flex-col ">
      <LocalNotificationBanner notification={notification} />

      <div class="sm:mx-auto sm:w-full sm:max-w-md">
        <h2 class="mt-6 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">
          <i18n.Translate>Create account</i18n.Translate>
        </h2>
      </div>

      <div class="mt-10 sm:mx-auto sm:w-full sm:max-w-[480px] ">
        <FormUI design={design} model={handler} />
        <div class="mt-8">
          <ButtonBetter
            type="submit"
            class="disabled:opacity-50 disabled:cursor-default flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
            onClick={create}
          >
            <i18n.Translate>Create</i18n.Translate>
          </ButtonBetter>
        </div>
      </div>
    </div>
  );
}
