import { createContext, useContext, ReactNode, useEffect } from "react";
import { useForm, FormProvider, SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { CourseDto, CourseLevel, CourseStatus } from "@nice/common";
import { api, useCourse } from "@nice/client";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
// 定义课程表单验证 Schema
const courseSchema = z.object({
    title: z.string().min(1, '课程标题不能为空'),
    subTitle: z.string().nullish(),
    description: z.string().nullish(),
    thumbnail: z.string().url().nullish(),
    level: z.nativeEnum(CourseLevel),
    requirements: z.array(z.string()).nullish(),
    objectives: z.array(z.string()).nullish()
});
export type CourseFormData = z.infer<typeof courseSchema>;
interface CourseEditorContextType {
	onSubmit: SubmitHandler<CourseFormData>;
	editId?: string; // 添加 editId
	part?: string;
	course?: CourseDto;
}
interface CourseFormProviderProps {
	children: ReactNode;
	editId?: string; // 添加 editId 参数
	part?: string;
}
const CourseEditorContext = createContext<CourseEditorContextType | null>(null);
export function CourseFormProvider({ children, editId }: CourseFormProviderProps) {
    const { create, update } = useCourse()
    const { data: course }: { data: CourseDto } = api.course.findFirst.useQuery({ where: { id: editId } }, { enabled: Boolean(editId) })
    const navigate = useNavigate()
    const methods = useForm<CourseFormData>({
        resolver: zodResolver(courseSchema),
        defaultValues: {
            level: CourseLevel.BEGINNER,
            requirements: [],
            objectives: []
        },
    });
    useEffect(() => {
        if (course) {
            const formData = {
                title: course.title,
                subTitle: course.subTitle,
                description: course.description,
                thumbnail: course.thumbnail,
                level: course.level,
                requirements: course.requirements,
                objectives: course.objectives,
                status: course.status,
            };
            methods.reset(formData as any);
        }
    }, [course, methods]);
    const onSubmit: SubmitHandler<CourseFormData> = async (data: CourseFormData) => {
        try {

            if (editId) {
                await update.mutateAsync({
                    where: { id: editId },
                    data: {
                        ...data
                    }
                })
                toast.success('课程更新成功！');
            } else {
                const result = await create.mutateAsync({
                    data: {
                        status: CourseStatus.DRAFT,
                        ...data
                    }
                })
                navigate(`/course/${result.id}/editor`, { replace: true })
                toast.success('课程创建成功！');
            }
            methods.reset(data);


        } catch (error) {
            console.error('Error submitting form:', error);
            toast.error('操作失败，请重试！');
        }
    };
    return (
        <CourseEditorContext.Provider value={{ onSubmit, editId, course }}>
            <FormProvider {...methods}>
                {children}
            </FormProvider>
        </CourseEditorContext.Provider>
    );
}

export const useCourseEditor = () => {
	const context = useContext(CourseEditorContext);
	if (!context) {
		throw new Error(
			"useCourseEditor must be used within CourseFormProvider"
		);
	}
	return context;
};
