import { create } from "zustand";
import { dispatchSocket } from "../../(app)/dispatch/socket";
import { useAudioStore } from "_store/audioStore";
import { ConnectedDispatcher } from "@repo/db";

interface ConnectionStore {
	status: "connected" | "disconnected" | "connecting" | "error";
	hideDraftMissions: boolean;
	setHideDraftMissions: (hide: boolean) => void;
	connectedDispatcher: ConnectedDispatcher | null;
	message: string;
	selectedZone: string;
	logoffTime: string;
	ghostMode: boolean;
	connect: (
		uid: string,
		selectedZone: string,
		logoffTime: string,
		ghostMode: boolean,
	) => Promise<void>;
	disconnect: () => void;
}

export const useDispatchConnectionStore = create<ConnectionStore>((set) => ({
	status: "disconnected",
	hideDraftMissions: false,
	setHideDraftMissions: (hide) => set({ hideDraftMissions: hide }),
	connectedDispatcher: null,
	message: "",
	selectedZone: "LST_01",
	logoffTime: "",
	ghostMode: false,
	connect: async (uid, selectedZone, logoffTime, ghostMode) =>
		new Promise((resolve) => {
			set({ status: "connecting", message: "" });
			dispatchSocket.auth = { uid };
			set({ selectedZone, logoffTime, ghostMode });
			dispatchSocket.connect();

			dispatchSocket.once("connect", () => {
				resolve();
			});
		}),
	disconnect: () => {
		dispatchSocket.disconnect();
	},
}));

dispatchSocket.on("connect", () => {
	const { logoffTime, selectedZone, ghostMode } = useDispatchConnectionStore.getState();
	useAudioStore.getState().connect("LST_01", selectedZone || "Leitstelle");
	dispatchSocket.emit("connect-dispatch", {
		logoffTime,
		selectedZone,
		ghostMode,
	});
	useDispatchConnectionStore.setState({ status: "connected", message: "" });
});

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

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

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

dispatchSocket.on("force-disconnect", (reason: string) => {
	useDispatchConnectionStore.setState({
		status: "disconnected",
		message: reason,
	});
});
dispatchSocket.on("own-dispatcher", (dispatch: ConnectedDispatcher) => {
	useDispatchConnectionStore.setState({
		connectedDispatcher: dispatch,
	});
});

dispatchSocket.on("reconnect", () => {});
