import { create } from "zustand";
import { dispatchSocket } from "../../dispatch/socket";
import { ConnectedAircraft, Mission, MissionSdsLog, Station, User } from "@repo/db";
import { pilotSocket } from "pilot/socket";
import { useDmeStore } from "_store/pilot/dmeStore";
import { useMrtStore } from "_store/pilot/MrtStore";
import { useAudioStore } from "_store/audioStore";

interface ConnectionStore {
	status: "connected" | "disconnected" | "connecting" | "error";
	message: string;
	logoffTime: string;
	selectedStation: Station | null;
	connectedAircraft: ConnectedAircraft | null;
	activeMission:
		| (Mission & {
				Stations: Station[];
		  })
		| null;
	connect: (
		uid: string,
		stationId: string,
		logoffTime: string,
		station: Station,
		user: User,
	) => Promise<void>;
	disconnect: () => void;
}

export const usePilotConnectionStore = create<ConnectionStore>((set) => ({
	status: "disconnected",
	message: "",
	logoffTime: "",
	selectedStation: null,
	connectedAircraft: null,
	activeMission: null,
	connect: async (uid, stationId, logoffTime, station, user) =>
		new Promise((resolve) => {
			set({
				status: "connecting",
				message: "",
				selectedStation: station,
				logoffTime,
			});

			pilotSocket.auth = { uid };
			pilotSocket.connect();
			pilotSocket.once("connect", () => {
				useDmeStore.getState().setPage({
					page: "home",
					station,
					user,
				});

				resolve();
			});
		}),
	disconnect: () => {
		pilotSocket.disconnect();
	},
}));

pilotSocket.on("connect", () => {
	usePilotConnectionStore.setState({ status: "connected", message: "" });
	const { logoffTime, selectedStation } = usePilotConnectionStore.getState();
	dispatchSocket.disconnect();
	useAudioStore.getState().connect("LST_01", selectedStation?.bosCallsignShort || "pilot");

	pilotSocket.emit("connect-pilot", {
		logoffTime,
		stationId: selectedStation?.id,
	});
});

pilotSocket.on("connect_error", (err) => {
	usePilotConnectionStore.setState({
		status: "error",
		message: err.message,
	});
});

pilotSocket.on("disconnect", () => {
	usePilotConnectionStore.setState({ status: "disconnected", message: "" });
	useAudioStore.getState().disconnect();
});

pilotSocket.on("force-disconnect", (reason: string) => {
	console.log("force-disconnect", reason);
	usePilotConnectionStore.setState({
		status: "disconnected",
		message: reason,
	});
});

pilotSocket.on("aircraft-update", (data) => {
	usePilotConnectionStore.setState({
		connectedAircraft: data,
	});
});

pilotSocket.on("mission-alert", (data: Mission & { Stations: Station[] }) => {
	usePilotConnectionStore.setState({
		activeMission: data,
	});
	useDmeStore.getState().setPage({
		page: "new-mission",
	});
});

pilotSocket.on("sds-message", (sdsMessage: MissionSdsLog) => {
	const station = usePilotConnectionStore.getState().selectedStation;
	if (!station) return;
	useMrtStore.getState().setPage({
		page: "sds",
		station,
		sdsMessage,
	});
});
