import dynamic from "next/dynamic";
import { useEffect, useRef, useState } from "react";
import { LoadingPage } from "~/components/loading";
import { getStorageUrl } from "~/lib/storage_utils";
import { cn } from "~/lib/utils";
import type { FileMetadata } from "~/server/services/storage.service";

const PDFViewer = dynamic(
	() => import("./pdf-viewer").then((mod) => mod.PDFViewer),
	{
		ssr: false,
		loading: () => <LoadingPage />,
	},
);
export const AllegatoIframe = ({
	className,
	allegato,
}: {
	className?: string;
	allegato: FileMetadata;
}) => {
	const if_ref = useRef<HTMLIFrameElement>(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.mimeType === "application/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";
			}
		}
	};

	const requestUrl = getStorageUrl({
		storageId: allegato.id,
		params: { mode: "inline" },
	});
	// 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>
	);
};
