import { createContext, useContext, ReactNode, useEffect } from "react";
import { Form, FormInstance, message } from "antd";
import {
	CourseDto,
	CourseStatus,
	ObjectType,
	PostType,
	Taxonomy,
} from "@nice/common";
import { api, usePost } from "@nice/client";
import { useNavigate } from "react-router-dom";
import { z } from "zod";

export type CourseFormData = {
	title: string;
	subTitle?: string;
	content?: string;
	thumbnail?: string;
	requirements?: string[];
	objectives?: string[];
	sections: any;
};

interface CourseEditorContextType {
	onSubmit: (values: CourseFormData) => Promise<void>;
	editId?: string;
	course?: CourseDto;
	taxonomies?: Taxonomy[]; // 根据实际类型调整
	form: FormInstance<CourseFormData>; // 添加 form 到上下文
}

interface CourseFormProviderProps {
	children: ReactNode;
	editId?: string;
}

const CourseEditorContext = createContext<CourseEditorContextType | null>(null);

export function CourseFormProvider({
	children,
	editId,
}: CourseFormProviderProps) {
	const [form] = Form.useForm<CourseFormData>();
	const { create, update, createCourse } = usePost();
	const { data: course }: { data: CourseDto } = api.post.findFirst.useQuery(
		{ where: { id: editId } },
		{ enabled: Boolean(editId) }
	);
	const {
		data: taxonomies,
	}: {
		data: Taxonomy[];
	} = api.taxonomy.getAll.useQuery({
		// type: ObjectType.COURSE,
	});
	const navigate = useNavigate();

	useEffect(() => {
		if (course) {
			const formData = {
				title: course.title,
				subTitle: course.subTitle,
				content: course.content,
				thumbnail: course?.meta?.thumbnail,
				requirements: course?.meta?.requirements,
				objectives: course?.meta?.objectives,
			};
			form.setFieldsValue(formData);
		}
	}, [course, form]);

	const onSubmit = async (values: CourseFormData) => {
		console.log(values);
		const sections = values?.sections || [];
		const formattedValues = {
			...values,
			meta: {
				requirements: values.requirements,
				objectives: values.objectives,
			},
		};
		delete formattedValues.requirements;
		delete formattedValues.objectives;
		delete formattedValues.sections;
		try {
			if (editId) {
				await update.mutateAsync({
					where: { id: editId },
					data: formattedValues,
				});
				message.success("课程更新成功！");
			} else {
				const result = await createCourse.mutateAsync({
					courseDetail: {
						data: {
							title: formattedValues.title || "12345",
							state: CourseStatus.DRAFT,
							type: PostType.COURSE,
							...formattedValues,
						},
					},
					sections,
				});
				navigate(`/course/${result.id}/editor`, { replace: true });
				message.success("课程创建成功！");
			}
			form.resetFields();
		} catch (error) {
			console.error("Error submitting form:", error);
			message.error("操作失败，请重试！");
		}
	};

	return (
		<CourseEditorContext.Provider
			value={{
				onSubmit,
				editId,
				course,
				taxonomies,
				form,
			}}>
			<Form
				form={form}
				onFinish={onSubmit}
				initialValues={{
					requirements: [],
					objectives: [],
				}}>
				{children}
			</Form>
		</CourseEditorContext.Provider>
	);
}

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