/*
 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 { TranslatedString } from "@gnu-taler/taler-util";
import {
  Footer,
  Header,
  ToastBanner,
  notifyError,
  notifyException,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { ComponentChildren, VNode, h } from "preact";
import { useEffect, useErrorBoundary } from "preact/hooks";
import { useUiSettingsContext } from "./context/ui-settings.js";
import { OfficerState } from "./hooks/officer.js";
import {
  getAllBooleanPreferences,
  getLabelForPreferences,
  usePreferences,
} from "./hooks/preferences.js";

const GIT_HASH = typeof __GIT_HASH__ !== "undefined" ? __GIT_HASH__ : undefined;
const VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : undefined;

const TALER_SCREEN_ID = 101;

function useErrorReport() {
  const { i18n } = useTranslationContext();
  const [error] = useErrorBoundary();

  useEffect(() => {
    if (error) {
      if (error instanceof Error) {
        notifyException(i18n.str`Internal error, please report.`, error);
      } else {
        notifyError(
          i18n.str`Internal error, please report.`,
          String(error) as TranslatedString,
        );
      }
      console.log(error);
    }
  }, [error]);
}

export function ExchangeAmlFrame({
  children,
  officer,
  NavigationBar: Navigation,
}: {
  officer?: OfficerState;
  children?: ComponentChildren;
  NavigationBar?: () => VNode;
}): VNode {
  const { i18n } = useTranslationContext();

  useErrorReport();

  const [preferences, updatePreferences] = usePreferences();
  const settings = useUiSettingsContext();

  return (
    <div class="min-h-full flex flex-col m-0 bg-slate-200 min-h-screen">
      <div class="bg-indigo-600 pb-32">
        <Header
          title="Exchange"
          iconLinkURL={settings.backendBaseURL ?? "#"}
          onLogout={
            officer?.state !== "ready"
              ? undefined
              : () => {
                  officer.lock();
                }
          }
          sites={[]}
        >
          <li>
            <div class="text-xs font-semibold leading-6 text-gray-400">
              <i18n.Translate>Preferences</i18n.Translate>
            </div>
            <ul role="list" class="space-y-1">
              {getAllBooleanPreferences().map((set) => {
                const isOn: boolean = !!preferences[set];
                return (
                  <li key={set} class="mt-2 pl-2">
                    <div class="flex items-center justify-between">
                      <span class="flex flex-grow flex-col">
                        <span
                          class="text-sm text-black font-medium leading-6 "
                          id="availability-label"
                        >
                          {getLabelForPreferences(set, i18n)}
                        </span>
                      </span>
                      <button
                        type="button"
                        data-enabled={isOn}
                        class="bg-indigo-600 data-[enabled=false]:bg-gray-200 relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2"
                        role="switch"
                        aria-checked="false"
                        aria-labelledby="availability-label"
                        aria-describedby="availability-description"
                        onClick={() => {
                          updatePreferences(set, !isOn);
                        }}
                      >
                        <span
                          aria-hidden="true"
                          data-enabled={isOn}
                          class="translate-x-5 data-[enabled=false]:translate-x-0 pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out"
                        ></span>
                      </button>
                    </div>
                  </li>
                );
              })}
            </ul>
          </li>
        </Header>
      </div>

      <div class="fixed z-20 w-full">
        <div class="mx-auto w-4/5">
          <ToastBanner debug={preferences.showDebugInfo} />
        </div>
      </div>

      <div class="-mt-32 flex grow ">
        {Navigation === undefined ? undefined : <Navigation />}
        <div class="flex mx-auto my-4 min-w-80">
          <main class="block rounded-lg bg-white px-5 py-6 shadow min-w-xl">
            {children}
          </main>
        </div>
      </div>

      <Footer
        testingUrlKey="aml-base-url"
        GIT_HASH={GIT_HASH}
        VERSION={VERSION}
      />
    </div>
  );
}
