/*
 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/>
 */

import { AbsoluteTime, MerchantPersona } from "@gnu-taler/taler-util";
import {
  useCommonPreferences,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { VNode, h } from "preact";
import {
  FormErrors,
  FormProvider,
} from "../../components/form/FormProvider.js";
import { InputSelector } from "../../components/form/InputSelector.js";
import { LangSelector } from "../../components/menu/LangSelector.js";
import { Preferences, usePreference } from "../../hooks/preference.js";
import { useSessionContext } from "../../context/session.js";
import { NotificationCard } from "../../components/menu/index.js";

const TALER_SCREEN_ID = 83;

type FormType = Preferences;
export function Settings({ onClose }: { onClose?: () => void }): VNode {
  const { i18n } = useTranslationContext();
  const { config } = useSessionContext();
  const [value, , updateValue] = usePreference();
  const [{ showDebugInfo }, updateCommonPref] = useCommonPreferences();
  const errors: FormErrors<FormType> = {};

  const formValue: typeof value = {
    ...value,
    persona: value.persona ?? config.default_persona,
  };

  function valueHandler(s: (d: Partial<FormType>) => Partial<FormType>): void {
    const next = s(formValue);
    const v: Preferences = {
      hideMissingAccountUntil:
        next.hideMissingAccountUntil ?? AbsoluteTime.never(),
      hideKycUntil: next.hideKycUntil ?? AbsoluteTime.never(),
      dateFormat: next.dateFormat ?? "ymd",
      persona: next.persona ?? config.default_persona,
    };

    const isDeveloper = next.persona === "developer";
    if (isDeveloper !== showDebugInfo) {
      updateCommonPref("showDebugInfo", isDeveloper);
    }

    updateValue(v);
  }

  return (
    <div>
      <section class="section is-main-section">
        <div class="columns">
          <div class="column" />
          <div class="column is-four-fifths">
            <div>
              <FormProvider<FormType>
                name="settings"
                errors={errors}
                object={formValue}
                valueHandler={valueHandler}
              >
                <div class="field is-horizontal">
                  <div class="field-label is-normal">
                    <label class="label">
                      <i18n.Translate>Language</i18n.Translate>
                      <span
                        class="icon has-tooltip-right"
                        data-tooltip={
                          "Force language setting instance of taking the browser"
                        }
                      >
                        <i class="mdi mdi-information" />
                      </span>
                    </label>
                  </div>
                  <div class="field field-body has-addons is-flex-grow-3">
                    <LangSelector />
                  </div>
                </div>
                <InputSelector<Preferences>
                  name="dateFormat"
                  label={i18n.str`Date format`}
                  expand={true}
                  help={
                    formValue.dateFormat === "dmy"
                      ? "31/12/2001"
                      : formValue.dateFormat === "mdy"
                        ? "12/31/2001"
                        : formValue.dateFormat === "ymd"
                          ? "2001/12/31"
                          : ""
                  }
                  toStr={(e) => {
                    if (e === "ymd") return "year month day";
                    if (e === "mdy") return "month day year";
                    if (e === "dmy") return "day month year";
                    return "choose one";
                  }}
                  values={["ymd", "mdy", "dmy"]}
                  tooltip={i18n.str`How the date is going to be displayed`}
                />
                <InputSelector<FormType>
                  label={i18n.str`Merchant type`}
                  tooltip={i18n.str`Simplify UI based on the user usage.`}
                  name="persona"
                  values={
                    [
                      "digital-publishing",
                      "e-commerce",
                      "offline-vending-machine",
                      "point-of-sale",
                      "expert",
                      "developer",
                    ] as MerchantPersona[]
                  }
                  toStr={(e: MerchantPersona) => {
                    switch (e) {
                      case "expert":
                        return i18n.str`Expert user`;
                      case "developer":
                        return i18n.str`Taler developer`;
                      case "offline-vending-machine":
                        return i18n.str`Unattended in-person offline vending`;
                      case "point-of-sale":
                        return i18n.str`In-person online point-of-sale with inventory`;
                      case "digital-publishing":
                        return i18n.str`Digital publishing`;
                      case "e-commerce":
                        return i18n.str`E-commerce site`;
                    }
                  }}
                />
              </FormProvider>
            </div>
            {value.persona === "developer" ? (
              <NotificationCard
                notification={{
                  message: i18n.str`Developer mode`,
                  description: i18n.str`Only use developer mode if you know how the application works. Some features enabled in this mode are still under testing.`,
                  type: "WARN",
                }}
              />
            ) : undefined}
          </div>
          <div class="column" />
        </div>
      </section>
      {onClose && (
        <section class="section is-main-section">
          <button type="button" class="button" onClick={onClose}>
            <i18n.Translate>Close</i18n.Translate>
          </button>
        </section>
      )}
    </div>
  );
}
