import { create } from "zustand";
import { dispatchSocket } from "../../(app)/dispatch/socket";
import { ConnectedAircraft, Mission, MissionSdsLog, Station, User } from "@repo/db";
import { showToast } from "../../_components/customToasts/HPGnotValidated";
import { pilotSocket } from "(app)/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;
	debug: boolean;
	logoffTime: string;
	selectedStation: Station | null;
	connectedAircraft: ConnectedAircraft | null;
	activeMission:
		| (Mission & {
				Stations: Station[];
		  })
		| null;
	connect: (
		uid: string,
		stationId: string,
		logoffTime: string,
		station: Station,
		user: User,
		debug?: boolean,
	) => Promise<void>;
	disconnect: () => void;
	followOwnAircraft: boolean;
	showOtherAircrafts: boolean;
	showOtherMissions: boolean;
	setMapOptions: (options: {
		followOwnAircraft?: boolean;
		showOtherAircrafts?: boolean;
		showOtherMissions?: boolean;
	}) => void;
}

export const usePilotConnectionStore = create<ConnectionStore>((set) => ({
	status: "disconnected",
	message: "",
	logoffTime: "",
	selectedStation: null,
	connectedAircraft: null,
	activeMission: null,
	debug: false,
	followOwnAircraft: false,
	showOtherAircrafts: false,
	showOtherMissions: false,
	setMapOptions(options) {
		set((state) => ({
			...state,
			...options,
		}));
	},
	connect: async (uid, stationId, logoffTime, station, user, debug) =>
		new Promise((resolve) => {
			set({
				status: "connecting",
				message: "",
				selectedStation: station,
				logoffTime,
				debug,
			});

			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, debug } = usePilotConnectionStore.getState();
	dispatchSocket.disconnect();
	useAudioStore.getState().connect("LST_01", selectedStation?.bosCallsignShort || "pilot");

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

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

pilotSocket.on("connect-message", (data) => {
	usePilotConnectionStore.setState({
		message: data.message,
	});
});

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

pilotSocket.on("force-disconnect", (reason: string) => {
	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",
	});
	if (
		data.hpgValidationState === "NOT_VALIDATED" &&
		usePilotConnectionStore.getState().connectedAircraft?.posH145active
	) {
		showToast();
	}
});

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