import { useEffect, useState } from "react";
import { Center, Loader, Stack, Text } from "@mantine/core";

import type { FaydaCallbackMessage } from "@/services/verifayda.service";

/**
 * Landing page for the eSignet redirect_uri (FAYDA_WEB_REDIRECT_URI →
 * http://localhost:5183/callback). Runs inside the verification popup:
 * relays ?code&state (or ?error) to the window that opened it via
 * postMessage, then closes itself. The opener performs the /complete call
 * so the single-use session is only consumed once, in one place.
 */
const FaydaCallbackPage = () => {
  const [standalone, setStandalone] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const message: FaydaCallbackMessage = {
      type: "fayda-callback",
      code: params.get("code") ?? undefined,
      state: params.get("state") ?? undefined,
      error: params.get("error") ?? undefined,
      errorDescription: params.get("error_description") ?? undefined,
    };

    if (window.opener && window.opener !== window) {
      (window.opener as Window).postMessage(message, window.location.origin);
      window.close();
    } else {
      // Opened as a full-page redirect instead of a popup — nothing to relay to.
      setStandalone(true);
    }
  }, []);

  return (
    <Center h="100vh">
      <Stack align="center" gap="sm">
        {standalone ? (
          <>
            <Text fw={600}>Verification window lost its parent page</Text>
            <Text size="sm" c="dimmed">
              Close this tab and restart the verification from the form.
            </Text>
          </>
        ) : (
          <>
            <Loader size="sm" />
            <Text size="sm" c="dimmed">Completing Fayda verification…</Text>
          </>
        )}
      </Stack>
    </Center>
  );
};

export default FaydaCallbackPage;
