import { api, useVisitor } from "@nice/client";
import {
	courseDetailSelect,
	CourseDto,
	Lecture,
	lectureDetailSelect,
	PostDto,
	RolePerms,
	VisitType,
} from "@nice/common";
import { useAuth } from "@web/src/providers/auth-provider";
import React, {
	createContext,
	ReactNode,
	useEffect,
	useMemo,
	useState,
} from "react";
import { useNavigate, useParams } from "react-router-dom";

interface CourseDetailContextType {
	editId?: string; // 添加 editId
	post?: PostDto;
	lecture?: Lecture;
	selectedLectureId?: string | undefined;
	setSelectedLectureId?: React.Dispatch<React.SetStateAction<string>>;
	isLoading?: boolean;
	lectureIsLoading?: boolean;
	isHeaderVisible: boolean; // 新增
	setIsHeaderVisible: (visible: boolean) => void; // 新增
	canEdit?: boolean;
	userIsLearning?: boolean;
	setUserIsLearning: (learning: boolean) => void;
}

interface CourseFormProviderProps {
	children: ReactNode;
	editId?: string; // 添加 editId 参数
}

export const CourseDetailContext =
	createContext<CourseDetailContextType | null>(null);
export function PostDetailProvider({
	children,
	editId,
}: CourseFormProviderProps) {
	const navigate = useNavigate();
	const { read } = useVisitor();
	const { user, hasSomePermissions, isAuthenticated } = useAuth();
	const { lectureId } = useParams();

	const { data: post, isLoading }: { data: PostDto; isLoading: boolean } = (
		api.post as any
	).findFirst.useQuery(
		{
			where: { id: editId },
			select: courseDetailSelect,
		},
		{ enabled: Boolean(editId) }
	);
	const [userIsLearning, setUserIsLearning] = useState(false);
	useEffect(() => {
		setUserIsLearning((post?.studentIds || []).includes(user?.id));
	}, [user, post, isLoading]);
	const canEdit = useMemo(() => {
		const isAuthor = isAuthenticated && user?.id === post?.authorId;
		const isRoot = hasSomePermissions(RolePerms?.MANAGE_ANY_POST);
		return isAuthor || isRoot;
	}, [user, post]);

	const [selectedLectureId, setSelectedLectureId] = useState<
		string | undefined
	>(lectureId || undefined);
	const { data: lecture, isLoading: lectureIsLoading } = (
		api.post as any
	).findFirst.useQuery(
		{
			where: { id: selectedLectureId },
			select: lectureDetailSelect,
		},
		{ enabled: Boolean(editId) }
	);

	useEffect(() => {
		if (lectureId) {
			read.mutateAsync({
				data: {
					visitorId: user?.id || null,
					postId: lectureId,
					type: VisitType.READED,
				},
			});
		} else {
			read.mutateAsync({
				data: {
					visitorId: user?.id || null,
					postId: editId,
					type: VisitType.READED,
				},
			});
		}
	}, [editId, lectureId]);
	useEffect(() => {
		if (lectureId !== selectedLectureId) {
			navigate(`/course/${editId}/detail/${selectedLectureId}`);
		}
	}, [selectedLectureId, editId]);
	const [isHeaderVisible, setIsHeaderVisible] = useState(true); // 新增
	useEffect(() => {
		console.log("post", post);
	}, [post]);
	return (
		<CourseDetailContext.Provider
			value={{
				editId,
				post,
				lecture,
				selectedLectureId,
				setSelectedLectureId,
				isLoading,
				lectureIsLoading,
				isHeaderVisible,
				setIsHeaderVisible,
				canEdit,
				userIsLearning,
				setUserIsLearning,
			}}>
			{children}
		</CourseDetailContext.Provider>
	);
}
