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

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

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

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

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

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

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

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

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