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

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 { user } = useAuth();
	const { data: course }: { data: CourseDto } = api.post.findFirst.useQuery(
		{
			where: { id: editId },
			select: courseDetailSelect,
		},
		{ enabled: Boolean(editId) }
	);
	const {
		data: taxonomies,
	}: {
		data: Taxonomy[];
	} = api.taxonomy.getAll.useQuery({
		type: ObjectType.COURSE,
	});
	const navigate = useNavigate();

	useEffect(() => {
		if (course) {
			const deptIds = (course?.depts || [])?.map((dept) => dept.id);
			const formData = {
				title: course.title,
				subTitle: course.subTitle,
				content: course.content,
				deptIds: deptIds,
				meta: {
					thumbnail: course?.meta?.thumbnail,
				},
			};
			course.terms?.forEach((term) => {
				formData[term.taxonomyId] = term.id; // 假设 taxonomyName 是您在 Form.Item 中使用的 name
			});
			form.setFieldsValue(formData);
		}
	}, [course, form]);

	const onSubmit = async (values: any) => {
		
		const sections = values?.sections || [];
		const deptIds = values?.deptIds || [];
		const termIds = taxonomies
			.map((tax) => values[tax.id]) // 获取每个 taxonomy 对应的选中值
			.filter((id) => id); // 过滤掉空值

		const formattedValues = {
			...values,
			type: PostType.COURSE,
			meta: {
				...((course?.meta as CourseMeta) || {}),
				...(values?.meta?.thumbnail !== undefined && {
					thumbnail: values?.meta?.thumbnail,
				}),
			},
			terms:
				termIds?.length > 0
					? {
							[editId ? "set" : "connect"]: termIds.map((id) => ({
								id,
							})), // 转换成 connect 格式
						}
					: undefined,
			depts:
				deptIds?.length > 0
					? {
							[editId ? "set" : "connect"]: deptIds.map((id) => ({
								id,
							})),
						}
					: undefined,
		};
		// 删除原始的 taxonomy 字段
		taxonomies.forEach((tax) => {
			delete formattedValues[tax.id];
		});
		delete formattedValues.sections;
		delete formattedValues.deptIds;

		try {
			if (editId) {
				const result = await update.mutateAsync({
					where: { id: editId },
					data: formattedValues,
				});
				message.success("课程更新成功！");
				navigate(`/course/${result.id}/editor/content`);
			} else {
				const result = await createCourse.mutateAsync({
					courseDetail: {
						data: {
							title: formattedValues.title,

							// state: CourseStatus.DRAFT,
							type: PostType.COURSE,
							...formattedValues,
						},
					},
					sections,
				});
				message.success("课程创建成功！");
				navigate(`/course/${result.id}/editor/content`);
			}
			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;
};
