import { useEffect, useRef, useState } from "react";
import { LoadingPage } from "~/components/loading";
import { cn } from "~/lib/utils";
import type { TempTokensToken } from "~/schemas/public/TempTokens";
import { api } from "~/utils/api";

export const AllegatoIframe = ({
	className,
	allegato,
}: {
	className?: string;
	allegato: string;
}) => {
	const if_ref = useRef<HTMLIFrameElement>(null);
	const { mutateAsync: getToken } = api.storage.getStorageToken.useMutation();
	const [token, setToken] = useState<TempTokensToken | null>(null);
	const handleIframeLoad = () => {
		if (if_ref.current?.contentWindow) {
			const img = if_ref.current.contentWindow.document.querySelector("img");
			if (img) {
				img.style.width = "100%";
				img.style.height = "100%";
				img.style.objectFit = "contain";
			}
		}
	};
	useEffect(() => {
		async function set() {
			const token = await getToken();
			setToken(token);
		}
		set().catch((e) => console.error(e));
	}, []);

	if (!token) return <LoadingPage />;

	const requestUrl = `/go-api/storage/get/${allegato}?token=${String(token)}`;

	return (
		<div
			className={cn(
				"flex h-full w-full items-center justify-center object-contain",
				className,
			)}
		>
			{/** biome-ignore lint/a11y/noNoninteractiveElementInteractions: <need interaction> */}
			<iframe
				title="Allegato"
				ref={if_ref}
				src={requestUrl}
				className="h-full w-full"
				onLoad={handleIframeLoad}
				allowFullScreen
			/>
		</div>
	);
};
