import { createContext, type FC, type ReactNode, useContext } from "react";
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { UsersId } from "~/schemas/public/Users";

import type { UserWAnagrafica } from "~/server/controllers/user.controller";
import { api } from "~/utils/api";

type UserViewContextType = UserWAnagrafica & { chatid: ChatsChatid | null };

export const UserViewContext = createContext<UserViewContextType | null>(null);

export const UserViewProvider: FC<{ children: ReactNode; userId: UsersId }> = ({
	children,
	userId,
}) => {
	const { data, isLoading } = api.users.getUser.useQuery({ id: userId });
	const { data: chatid, isLoading: chatLoading } =
		api.chat.getChatIdByUser.useQuery({ userId });
	if ((!isLoading && !data) || (!chatLoading && chatid === undefined)) {
		throw new Error("Utente non trovato");
	}
	if (!isLoading && data && !chatLoading && chatid !== undefined) {
		return (
			<UserViewContext.Provider value={{ ...data, chatid }}>
				{children}
			</UserViewContext.Provider>
		);
	}
	return null;
};

export const useUserViewContext = () => {
	const context = useContext(UserViewContext);
	if (!context) {
		throw new Error(
			"useUserViewContext must be used within a UserViewProvider",
		);
	}
	return context;
};
