import { create } from "zustand";
import { ChatMessage } from "@repo/db";
import { dispatchSocket } from "dispatch/socket";
import { pilotSocket } from "pilot/socket";

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) => Promise<void>;
	addChat: (userId: string, name: string) => void;
	addMessage: (userId: string, message: ChatMessage) => 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) => set({ selectedChat: chatId }),
	setOwnId: (id: string) => set({ ownId: id }),
	chats: {},
	sendMessage: (userId: string, message: string) => {
		return new Promise((resolve, reject) => {
			dispatchSocket.emit("send-message", { userId, message }, ({ 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;
		console.log("setChatNotification", userId, notification);
		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: !isSender && (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();
		console.log("chat-message", userId, message);
		// 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();
	console.log("chat-message", userId, message);
	// Update the chat store with the new message
	store.addMessage(userId, message);
});
