import { ConnectedAircraft } from "@repo/db";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { useMrtStore } from "_store/pilot/MrtStore";
import { pilotSocket } from "pilot/socket";
import { editConnectedAircraftAPI } from "_querys/aircrafts";
import { useEffect } from "react";

export const useButtons = () => {
	const station = usePilotConnectionStore((state) => state.selectedStation);
	const connectedAircraft = usePilotConnectionStore((state) => state.connectedAircraft);
	const connectionStatus = usePilotConnectionStore((state) => state.status);

	const { page, setPage } = useMrtStore((state) => state);

	const handleButton =
		(button: "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "0") => () => {
			if (connectionStatus !== "connected") return;
			if (!station) return;
			if (!connectedAircraft?.id) return;
			if (
				button === "1" ||
				button === "2" ||
				button === "3" ||
				button === "4" ||
				button === "5" ||
				button === "6" ||
				button === "7" ||
				button === "8" ||
				button === "9" ||
				button === "0"
			) {
				if (page !== "home") return;
				setPage({ page: "sending-status", station });

				setTimeout(async () => {
					await editConnectedAircraftAPI(connectedAircraft!.id, {
						fmsStatus: button,
					});
					setPage({
						page: "home",
						station,
						fmsStatus: button,
					});
				}, 1000);
			}
		};

	useEffect(() => {
		pilotSocket.on("connect", () => {
			if (!station) return;
			setPage({ page: "home", fmsStatus: "6", station });
		});

		pilotSocket.on("aircraft-update", () => {
			if (!station) return;
			setPage({ page: "new-status", station });
		});
	}, [setPage, station]);

	return { handleButton };
};
