import { api } from "@nice/client";
import { courseDetailSelect, CourseDto, Lecture } from "@nice/common";
import React, { createContext, ReactNode, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

interface CourseDetailContextType {
	editId?: string; // 添加 editId
	course?: CourseDto;
	lecture?: Lecture;
	selectedLectureId?: string | undefined;
	setSelectedLectureId?: React.Dispatch<React.SetStateAction<string>>;
	isLoading?: boolean;
	lectureIsLoading?: boolean;
	isHeaderVisible: boolean; // 新增
	setIsHeaderVisible: (visible: boolean) => void; // 新增
}
interface CourseFormProviderProps {
	children: ReactNode;
	editId?: string; // 添加 editId 参数
}
export const CourseDetailContext =
	createContext<CourseDetailContextType | null>(null);
export function CourseDetailProvider({
	children,
	editId,
}: CourseFormProviderProps) {
	const navigate = useNavigate();
	const { data: course, isLoading }: { data: CourseDto; isLoading: boolean } =
		(api.post as any).findFirst.useQuery(
			{
				where: { id: editId },
				include: {
					// sections: { include: { lectures: true } },
					enrollments: true,
				},
			},
			{ enabled: Boolean(editId) }
		);
	const [selectedLectureId, setSelectedLectureId] = useState<
		string | undefined
	>(undefined);
	const { data: lecture, isLoading: lectureIsLoading } = (
		api.post as any
	).findFirst.useQuery(
		{
			where: { id: selectedLectureId },
		},
		{ enabled: Boolean(editId) }
	);
	useEffect(() => {
		navigate(`/course/${editId}/detail/${selectedLectureId}`);
	}, [selectedLectureId, editId]);
	const [isHeaderVisible, setIsHeaderVisible] = useState(true); // 新增
	return (
		<CourseDetailContext.Provider
			value={{
				editId,
				course,
				lecture,
				selectedLectureId,
				setSelectedLectureId,
				isLoading,
				lectureIsLoading,
				isHeaderVisible,
				setIsHeaderVisible,
			}}>
			{children}
		</CourseDetailContext.Provider>
	);
}
