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

/**
 * mapping route to view
 * not found (error page)
 * nested, index element, relative routes
 * link interception
 * form POST interception, call action
 * fromData => Object.fromEntries
 * segments in the URL
 * navigationState: idle, submitting, loading
 * form GET interception: does a navigateTo
 * form GET Sync:
 *   1.- back after submit: useEffect to sync URL to form
 *   2.- refresh after submit: input default value
 * useSubmit for form submission onChange, history replace
 *
 * post form without redirect
 *
 *
 * @param param0
 * @returns
 */

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

/**
 * TO BE FIXED:
 *
 * 1.- when the form change to other form and both form share the same structure
 * the same input component may be rendered in the same place,
 * since input are uncontrolled the are not re-rendered and since they are
 * uncontrolled it will keep the value of the previous form.
 * One solutions could be to remove the form when unloading and when the new
 * form load it will start without previous vdom, preventing the cache
 * to create this behavior.
 * Other solutions could be using IDs in the fields that are constructed
 * with the ID of the form, so two fields of different form will need to re-render
 * cleaning up the state of the previous form.
 *
 * 2.- currently the design prop and the behavior prop of the flexible form
 * are two side of the same coin. From the design point of view, it is important
 * to design the form in a list-of-field manner and there may be additional
 * content that is not directly mapped to the form structure (object)
 * So maybe we want to change the current shape so the computation of the state
 * of the form is in a field level, but this computation required the field value and
 * the whole form values and state (since one field may be disabled/hidden) because
 * of the value of other field.
 *
 * 3.- given the previous requirement, maybe the name of the field of the form could be
 * a function (P: F -> V) where F is the form (or parent object) and V is the type of the
 * property. That will help with the typing of the forms props
 *
 * 4.- tooltip are not placed correctly: the arrow should point the question mark
 * and the text area should be bigger
 *
 */

/**
 * check this fields
 *
 * Signature of Contracting partner, 902_9e
 * Currency and amount of deposited assets, 902_5e
 * Signature on declaration of trust, 902.13e
 * also fundations
 * also life insurance
 *
 * no all state are handled by all the inputs
 * all the input implementation should respect
 * ui props and state
 */

export function ExchangeAmlFrame({
  children,
  officer,
}: {
  officer?: OfficerState,
  children?: ComponentChildren;
}): VNode {
  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);
      // resetError()
    }
  }, [error]);

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

  return (
    <div
      class="min-h-full flex flex-col m-0 bg-slate-200"
      style="min-height: 100vh;"
    >
      <div class="bg-indigo-600 pb-32">
        <Header
          title="Exchange"
          iconLinkURL={settings.backendBaseURL ?? "#"}
          onLogout={
            officer?.state !== "ready"
              ? undefined
              : () => {
                  officer.lock();
                }
          }
          sites={[]}
          supportedLangs={["en", "es", "de"]}
        >
          <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 />
        </div>
      </div>

      <div class="-mt-32 flex grow ">
        {officer?.state !== "ready" ? undefined : <Navigation />}
        <div class="flex mx-auto my-4">
          <main class="rounded-lg bg-white px-5 py-6 shadow">{children}</main>
        </div>
      </div>

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

function Navigation(): VNode {
  const { i18n } = useTranslationContext();
  const pageList = [
    { route: privatePages.account, Icon: HomeIcon, label: i18n.str`Account` },
    { route: privatePages.cases, Icon: HomeIcon, label: i18n.str`Cases` },
  ];
  const { path } = useNavigationContext();
  return (
    <div class="hidden sm:block min-w-min bg-indigo-600 divide-y rounded-r-lg divide-cyan-800 overflow-y-auto overflow-x-clip">
      <nav class="flex flex-1 flex-col mx-4 mt-4 mb-2">
        <ul role="list" class="flex flex-1 flex-col gap-y-7">
          <li>
            <ul role="list" class="-mx-2 space-y-1">
              {pageList.map((p, idx) => {
                return (
                  <li key={idx}>
                    <a
                      href={p.route.url({})}
                      data-selected={path == p.route.url({})}
                      class="data-[selected=true]:bg-indigo-700 pr-4 data-[selected=true]:text-white  text-indigo-200 hover:text-white hover:bg-indigo-700   group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold"
                    >
                      {p.Icon && <p.Icon />}
                      <span class="hidden md:inline">{p.label}</span>
                    </a>
                  </li>
                );
              })}
              {/* <li>
                <a href="#" class="text-indigo-200 hover:text-white hover:bg-indigo-700 group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold">

                  <i18n.Translate>Officer</i18n.Translate>
                </a>
              </li> */}
            </ul>
          </li>

          {/* <li class="mt-auto ">
            <a href="#" class="group -mx-2 flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-indigo-200 hover:bg-indigo-700 hover:text-white">
              <svg class="h-6 w-6 shrink-0 text-indigo-200 group-hover:text-white" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
                <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              Settings
            </a>
          </li> */}
        </ul>
      </nav>
    </div>
  );
}
