import { api, usePost } from "@nice/client";
import { Post, postDetailSelect, PostDto, UserProfile } from "@nice/common";
import { useAuth } from "@web/src/providers/auth-provider";
import React, { createContext, ReactNode, useEffect, useState } from "react";
import { PostParams } from "@nice/client/src/singleton/DataHolder";

interface PostDetailContextType {
	editId?: string;
	post?: PostDto;
	isLoading?: boolean;
	user?: UserProfile;
}
interface PostFormProviderProps {
	children: ReactNode;
	editId?: string;
}
export const PostDetailContext = createContext<PostDetailContextType | null>(
	null
);
export function PostDetailProvider({
	children,
	editId,
}: PostFormProviderProps) {
	const { user } = useAuth();
	const postParams = PostParams.getInstance();
	const queryParams = {
		where: { id: editId },
		select: postDetailSelect,
	};

	useEffect(() => {
		if (editId) {
			postParams.addDetailItem(queryParams);
		}
		return () => {
			if (editId) {
				postParams.removeDetailItem(queryParams);
			}
		};
	}, [editId]);

	const { data: post, isLoading }: { data: PostDto; isLoading: boolean } = (
		api.post.findFirst as any
	).useQuery(queryParams, { enabled: Boolean(editId) });
	
	return (
		<PostDetailContext.Provider
			value={{
				editId,
				post,
				user,
				isLoading,
			}}>
			{children}
		</PostDetailContext.Provider>
	);
}
