"use client";
import { redirect, useSearchParams } from "next/navigation";
import { Service } from "../page";
import { generateToken } from "./action";
import { useSession } from "next-auth/react";
import { useErrorBoundary } from "react-error-boundary";

export const Authorize = ({ service }: { service: Service }) => {
	const { showBoundary } = useErrorBoundary();
	const searchParams = useSearchParams();
	const legitimeUrl = service.approvedUrls.some((url) =>
		searchParams.get("redirect_uri")?.startsWith(url),
	);
	const { data: session } = useSession();
	if (!session)
		redirect("/login?redirect=" + encodeURIComponent(window.location.href));
	if (!legitimeUrl)
		return (
			<div className="card-body">
				<h1 className="text-4xl font-bold">Unerlaubter Zugriff</h1>
				<p>Du greifst von einem nicht genehmigtem Server auf diese URL zu</p>
			</div>
		);

	return (
		<form className="card-body" onSubmit={(e) => e.preventDefault()}>
			<h1 className="text-4xl font-bold">Zugriff zulassen</h1>
			<p>
				Die Anwendung <strong>{service.name}</strong> möchte auf deine Daten
				zugreifen.
			</p>
			<div className="space-x-4">
				<button type="button" className="btn">
					Verweigern
				</button>
				<button
					type="submit"
					className="btn btn-primary"
					onClick={async () => {
						try {
							const code = await generateToken(service);
							const url = new URL(searchParams.get("redirect_uri") as string);
							url.searchParams.append("code", code?.accessToken as string);
							url.searchParams.append(
								"state",
								searchParams.get("state") as string,
							);

							window.location.href = url.href;
						} catch (error) {
							showBoundary(error);
						}
					}}
				>
					Zulassen
				</button>
			</div>
		</form>
	);
};
