import dynamic from "next/dynamic";
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";

const PDFViewer = dynamic(
	() => import("./pdf-viewer").then((mod) => mod.PDFViewer),
	{
		ssr: false,
		loading: () => <LoadingPage />,
	},
);
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 [isMobile, setIsMobile] = useState(false);
	const [isIOS, setIsIOS] = useState(false);
	const [isPDF, setIsPDF] = useState(false);

	useEffect(() => {
		// Detect mobile and iOS
		const userAgent = navigator.userAgent.toLowerCase();
		setIsMobile(
			/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(
				userAgent,
			),
		);
		setIsIOS(/iphone|ipad|ipod/i.test(userAgent));

		// Try to detect if file is PDF from extension
		setIsPDF(allegato.toLowerCase().endsWith(".pdf"));
	}, [allegato]);

	const handleIframeLoad = () => {
		if (if_ref.current?.contentWindow) {
			// For images
			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)}`;
	// For PDF on iOS, provide download link instead
	if (isPDF && (isIOS || isMobile)) {
		return (
			<div
				className={cn(
					"flex h-full w-full items-center justify-center object-contain",
					className,
				)}
			>
				<PDFViewer url={requestUrl} />
			</div>
		);
	}

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