/*
 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 {
  Loading,
  urlPattern,
  useCurrentLocation,
  useNavigationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";

import { assertUnreachable } from "@gnu-taler/taler-util";
import { useErrorBoundary } from "preact/hooks";
import { useSessionState } from "./hooks/session.js";
import { ChallengeCompleted } from "./pages/ChallengeCompleted.js";
import { Frame } from "./pages/Frame.js";
import { Start } from "./pages/Start.js";
import { TriggerForms } from "./pages/TriggerForms.js";
import { TriggerKyc } from "./pages/TriggerKyc.js";

export function Routing(): VNode {
  // check session and defined if this is
  // public routing or private
  return (
    <Frame
      routeTestForms={publicPages.triggerForm}
      routeTestKyc={publicPages.triggerKyc}
    >
      <PublicRounting />
    </Frame>
  );
}

/**
 * FIXME: Exporting this constant make typescript throw an error
 *
 * src/Routing.tsx:47:14 - error TS2742: The inferred type of 'publicPages' cannot be named without a reference to '../node_modules/@gnu-taler/web-util/src/index.browser.js'. This is likely not portable. A type annotation is necessary.
 */
const publicPages = {
  completed: urlPattern(/\/completed/, () => `#/completed`),
  start: urlPattern(/\/start/, () => `#/start`),
  triggerKyc: urlPattern(/\/test\/trigger-kyc/, () => `#/test/trigger-kyc`),
  triggerForm: urlPattern(
    /\/test\/show-forms\/(?<fid>[a-zA-Z0-9-_]+)/,
    ({ fid }) => `#/test/show-forms/${fid}`,
  ),
};

export function safeToURL(s: string | undefined): URL | undefined {
  if (s === undefined) return undefined;
  try {
    return new URL(s);
  } catch (e) {
    return undefined;
  }
}

function PublicRounting(): VNode {
  const location = useCurrentLocation(publicPages);
  const { state, start } = useSessionState();
  const { navigateTo } = useNavigationContext();
  useErrorBoundary((e) => {
    console.log("error", e);
  });
  const currentToken = state?.accessToken;
  switch (location.name) {
    case undefined: {
      navigateTo(publicPages.start.url({}));
      return <Loading />;
    }
    case "start": {
      if (!currentToken) {
        return <div>No access token</div>;
      }

      return <Start token={currentToken} />;
    }
    case "completed": {
      return <ChallengeCompleted />;
    }
    case "triggerKyc": {
      return (
        <TriggerKyc
          onKycStarted={(token) => {
            start(token);
            navigateTo(publicPages.start.url({}));
          }}
        />
      );
    }
    case "triggerForm": {
      return <TriggerForms formId={location.values.fid} />;
    }
    default:
      assertUnreachable(location);
  }
}
