/*
 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 { CheckChallengeIsUpToDate } from "./components/CheckChallengeIsUpToDate.js";
import { SessionId, useSessionState } from "./hooks/session.js";
import { AnswerChallenge } from "./pages/AnswerChallenge.js";
import { AskChallenge } from "./pages/AskChallenge.js";
import { CallengeCompleted } from "./pages/CallengeCompleted.js";
import { Frame } from "./pages/Frame.js";
import { NonceNotFound } from "./pages/NonceNotFound.js";
import { Setup } from "./pages/Setup.js";

export function Routing(): VNode {
  // check session and defined if this is
  // public routing or private
  return (
    <Frame>
      <PublicRounting />
    </Frame>
  );
}

const publicPages = {
  noinfo: urlPattern(/\/noinfo/, () => `#/noinfo`),
  authorize: urlPattern(/\/authorize/, () => `#/authorize`),
  ask: urlPattern(/\/ask/, () => `#/ask`),
  answer: urlPattern(/\/answer/, () => `#/answer`),
  completed: urlPattern(/\/completed/, () => `#/completed`),
  setup: urlPattern<{ client: string }>(
    /\/setup\/(?<client>[0-9]+)/,
    ({ client }) => `#/setup/${client}`,
  ),
};

function safeGetParam(
  ps: Record<string, string[]>,
  n: string,
): string | undefined {
  if (!ps[n] || ps[n].length == 0) return undefined;
  return ps[n][0];
}

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 { navigateTo } = useNavigationContext();
  const { start } = useSessionState();
  useErrorBoundary((e) => {
    console.log("error", e);
  });

  if (location === undefined) {
    return <NonceNotFound />;
  }

  switch (location.name) {
    case "noinfo": {
      return <div>no info</div>;
    }
    case "setup": {
      const secret = safeGetParam(location.params, "secret");
      const redirectURL = safeToURL(
        safeGetParam(location.params, "redirect_url"),
      );

      return (
        <Setup
          clientId={location.values.client}
          secret={secret}
          // redirect_url=http://exchange.taler.test:1180/kyc-proof/kyc-provider-wallet&secret=chal-secret
          redirectURL={redirectURL}
          onCreated={() => {
            navigateTo(publicPages.ask.url({}));
          }}
        />
      );
    }
    case "authorize": {
      const clientId = safeGetParam(location.params, "client_id");
      const redirectURL = safeToURL(
        safeGetParam(location.params, "redirect_url"),
      );
      const state = safeGetParam(location.params, "state");

      const sessionId: SessionId | undefined =
        !clientId || !redirectURL || !state
          ? undefined
          : {
              clientId,
              nonce: location.values.nonce,
              redirectURL: redirectURL.href,
              state,
            };

      return (
        <CheckChallengeIsUpToDate
          session={sessionId}
          onCompleted={() => {
            navigateTo(
              publicPages.completed.url({
                nonce: location.values.nonce,
              }),
            );
          }}
          onChangeLeft={() => {
            navigateTo(
              publicPages.ask.url({
                nonce: location.values.nonce,
              }),
            );
          }}
          onNoMoreChanges={() => {
            navigateTo(
              publicPages.ask.url({
                nonce: location.values.nonce,
              }),
            );
          }}
        >
          <Loading />
        </CheckChallengeIsUpToDate>
      );
    }
    case "ask": {
      return (
        <CheckChallengeIsUpToDate>
          <AskChallenge
            focus
            routeSolveChallenge={publicPages.answer}
            onSendSuccesful={() => {
              navigateTo(
                publicPages.answer.url({
                  nonce: location.values.nonce,
                }),
              );
            }}
            // onCompleted={() => {
            //   navigateTo(
            //     publicPages.completed.url({
            //       nonce: location.values.nonce,
            //     }),
            //   );
            // }}
          />
        </CheckChallengeIsUpToDate>
      );
    }
    case "answer": {
      return (
        <CheckChallengeIsUpToDate>
          <AnswerChallenge
            focus
            routeAsk={publicPages.ask}
            onComplete={() => {
              navigateTo(
                publicPages.completed.url({
                  nonce: location.values.nonce,
                }),
              );
            }}
            // onCompleted={() => {
            //   navigateTo(
            //     publicPages.completed.url({
            //       nonce: location.values.nonce,
            //     }),
            //   );
            // }}
          />
        </CheckChallengeIsUpToDate>
      );
    }
    case "completed": {
      return (
        <CheckChallengeIsUpToDate>
          <CallengeCompleted />
        </CheckChallengeIsUpToDate>
      );
    }
    default:
      assertUnreachable(location);
  }
}
