import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { AlertTriangle } from "lucide-react";
import { useEffect, useState } from "react";

export const SimConnectionAlert = ({ lastUpdated }: { lastUpdated?: Date }) => {
	const [lastHearbeetSeconds, setLastHearbeetSeconds] = useState(0);
	const { disconnect } = usePilotConnectionStore((state) => state);
	useEffect(() => {
		const interval = setInterval(() => {
			if (lastUpdated) {
				const now = new Date();
				const diff = Math.floor((now.getTime() - new Date(lastUpdated).getTime()) / 1000);
				setLastHearbeetSeconds(diff);
			} else {
				setLastHearbeetSeconds(0);
			}
		}, 1000);

		return () => clearInterval(interval);
	}, [lastUpdated]);

	return (
		<div role="alert" className="alert">
			<AlertTriangle className="w-6 h-6" />
			<div>
				<h3 className="font-bold">
					Keine Simulator Verbindung{" "}
					{lastHearbeetSeconds ? `seit ${lastHearbeetSeconds} Sekunden` : "gefunden"}
				</h3>
				<div className="text-xs">
					Wenn dein Simulator abgestürzt ist informiere den Disponenten über den Chat links
				</div>
			</div>
			<button className="btn btn-sm btn-warning" onClick={() => disconnect()}>
				Verbindung trennen
			</button>
		</div>
	);
};
