import { create } from "zustand";
import { ChatMessage } from "@repo/db";
import { dispatchSocket } from "(app)/dispatch/socket";
import { pilotSocket } from "(app)/pilot/socket";
import { useDispatchConnectionStore } from "_store/dispatch/connectionStore";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";

interface ChatStore {
	situationTabOpen: boolean;
	setSituationTabOpen: (open: boolean) => void;
	reportTabOpen: boolean;
	setReportTabOpen: (open: boolean) => void;
	ownId: null | string;
	selectedChat: string | null;
	chatOpen: boolean;
	setChatOpen: (open: boolean) => void;
	setSelectedChat: (chatId: string | null) => void;
	setOwnId: (id: string) => void;
	chats: Record<string, { name: string; notification: boolean; messages: ChatMessage[] }>;
	setChatNotification: (userId: string, notification: boolean) => void;
	sendMessage: (
		userId: string,
		message: string,
		senderName?: string,
		receiverName?: string,
	) => Promise<void>;
	addChat: (userId: string, name: string) => void;
	addMessage: (userId: string, message: ChatMessage) => void;
	removeChat: (userId: string) => void;
}

export const useLeftMenuStore = create<ChatStore>((set, get) => ({
	situationTabOpen: false,
	setSituationTabOpen: (open: boolean) => set({ situationTabOpen: open }),
	reportTabOpen: false,
	setReportTabOpen: (open: boolean) => set({ reportTabOpen: open }),
	ownId: null,
	chatOpen: false,
	selectedChat: null,
	setChatOpen: (open: boolean) => set({ chatOpen: open }),
	setSelectedChat: (chatId: string | null) => {
		const { setChatNotification } = get();
		set({ selectedChat: chatId });
		if (chatId) {
			setChatNotification(chatId, false); // Set notification to false when chat is selected
		}
	},
	removeChat: (userId: string) => {
		const { chats, setSelectedChat, selectedChat } = get();
		const newChats = { ...chats };
		delete newChats[userId];
		set({ chats: newChats });
		if (selectedChat === userId) {
			setSelectedChat(null);
		}
	},
	setOwnId: (id: string) => set({ ownId: id }),
	chats: {},
	sendMessage: (userId, message) => {
		return new Promise((resolve, reject) => {
			if (dispatchSocket.connected) {
				const zone = useDispatchConnectionStore.getState().selectedZone;
				dispatchSocket.emit(
					"send-message",
					{ userId, message, role: zone },
					({ error }: { error?: string }) => {
						if (error) {
							reject(error);
						} else {
							resolve();
						}
					},
				);
			} else if (pilotSocket.connected) {
				const bosCallsign = usePilotConnectionStore.getState().selectedStation?.bosCallsignShort;

				pilotSocket.emit(
					"send-message",
					{ userId, message, role: bosCallsign },
					({ error }: { error?: string }) => {
						if (error) {
							reject(error);
						} else {
							resolve();
						}
					},
				);
			}
		});
	},
	addChat: (userId, name) => {
		set((state) => ({
			chats: {
				...state.chats, // Bestehende Chats beibehalten
				[userId]: { name, notification: false, messages: [] }, // Neuen Chat hinzufügen
			},
		}));
	},
	setChatNotification: (userId, notification) => {
		const chat = get().chats[userId];
		if (!chat) return;
		set((state) => {
			return {
				chats: {
					...state.chats,
					[userId]: {
						...chat,
						notification,
					},
				},
			};
		});
	},
	addMessage: (userId: string, message: ChatMessage) => {
		set((state) => {
			const user = state.chats[userId] || {
				name: userId,
				messages: [],
				notification: false,
			};
			const isSender = message.senderId === state.ownId;

			return {
				selectedChat: state.selectedChat ? state.selectedChat : userId,
				chats: {
					...state.chats,
					[userId]: {
						...user,
						name: isSender ? message.receiverName : message.senderName,
						notification: state.selectedChat !== userId || !state.chatOpen,
						messages: [...user.messages, message], // Neuen Zustand erzeugen
					},
				},
			};
		});
	},
}));

dispatchSocket.on(
	"chat-message",
	({ userId, message }: { userId: string; message: ChatMessage }) => {
		const store = useLeftMenuStore.getState();
		// Update the chat store with the new message
		store.addMessage(userId, message);
	},
);
pilotSocket.on("chat-message", ({ userId, message }: { userId: string; message: ChatMessage }) => {
	const store = useLeftMenuStore.getState();
	// Update the chat store with the new message
	store.addMessage(userId, message);
});
