"use client";

import { useEffect, useState, useSyncExternalStore } from "react";
import { closeGameLaunch, getGameLaunchState, subscribeGameLaunch } from "@/components/providers/game-launch-store";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import { RobloxLogoIcon } from "@/components/roblox/RobloxIcons";
import Link from "next/link";

export function GameLaunchDialog() {
	const state = useSyncExternalStore(
		subscribeGameLaunch,
		getGameLaunchState,
		getGameLaunchState
	);

	const [launchTimeouted, setLaunchTimeouted] = useState<boolean>(false);

	useEffect(() => {
		if (!state.isOpen) {
			setLaunchTimeouted(false);
			return;
		}

		const timeout = setTimeout(() => {
			setLaunchTimeouted(true);
		}, 5000); // 5 seconds

		return () => clearTimeout(timeout);
	}, [state.isOpen]);

	if (!state.isOpen) return null;

	return (
		<div
			className="fixed inset-0 z-50 flex items-center justify-center bg-mantle/70 backdrop-blur-sm"
			onClick={closeGameLaunch}
		>
			<div
				className="relative w-[92vw] max-w-sm rounded-2xl bg-crust/95 ring-1 ring-surface0/60 shadow-2xl"
				onClick={(event) => event.stopPropagation()}
			>
				<Button
					variant="ghost"
					size="icon"
					onClick={closeGameLaunch}
					aria-label="Close launcher"
					className="absolute right-3 top-3"
				>
					<X className="h-4 w-4" />
				</Button>
				<div className="flex flex-col items-center gap-4 px-6 py-8 text-center">
					<div className="h-24 w-24 flex items-center justify-center">
						<RobloxLogoIcon />
					</div>
					<div className="space-y-1">
						<p className="text-2xl font-semibold text-text">
							{!launchTimeouted ? (
								<>
									Roblox is now loading.<br />Get Ready!
								</>
							) : (
								<>Download Roblox to play millions of experiences!</>
							)}
						</p>
					</div>
					<Button disabled={!launchTimeouted} variant="default" className="w-full rounded-full">
						{launchTimeouted ? (
							<Link href="https://flathub.org/en/apps/org.vinegarhq.Sober" target="_blank" rel="noopener noreferrer">
								Download Roblox
							</Link>
						) : null}
						{!launchTimeouted && <div className="h-4 w-4 rounded-full border-2 border-white/70 border-t-transparent animate-spin" />}
					</Button>
				</div>
			</div>
		</div>
	);
}
