import {
	PlusOutlined,
	DragOutlined,
	DeleteOutlined,
	CaretRightOutlined,
	SaveOutlined,
} from "@ant-design/icons";
import {
	Form,
	Alert,
	Button,
	Input,
	Select,
	Space,
	Collapse,
	message,
} from "antd";
import React, { useCallback, useEffect, useState } from "react";
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
	DragEndEvent,
} from "@dnd-kit/core";
import { api, emitDataChange } from "@nice/client";
import {
	arrayMove,
	SortableContext,
	sortableKeyboardCoordinates,
	useSortable,
	verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "../../../../common/editor/quill/QuillEditor";
import { TusUploader } from "../../../../common/uploader/TusUploader";
import { Lecture, LectureType, PostType } from "@nice/common";
import { useCourseEditor } from "../context/CourseEditorContext";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";
interface SectionData {
	id: string;
	title: string;
	content?: string;
	courseId?: string;
}

interface LectureData {
	id: string;
	title: string;
	type?: LectureType;
	content?: string;
	sectionId?: string;
}
const useCourseActions = () => {
	const { create, update, softDeleteByIds } = usePost();

	const softDeleteById = useCallback(
		async (id: string) => {
			console.log("oftDeleteById");
			softDeleteByIds.mutateAsync(
				{
					ids: [id],
				}
				// {
				// 	onSettled: () => {
				// 		message.success("删除成功");
				// 		emitDataChange(
				// 			ObjectType.DEPARTMENT,
				// 			props.data as any,
				// 			CrudOperation.DELETED
				// 		);
				// 	},
				// }
			);
			return;
			// return Promise.resolve({ id: "1", title: values.title || "" });
		},
		[update]
	);
	const updateSection = useCallback(
		(values: Partial<SectionData>) => {
			console.log("updateSection", values);
			return Promise.resolve({ id: "1", title: values.title || "" });
		},
		[update]
	);

	const createSection = useCallback(
		async (values: Partial<SectionData>, courseId: string) => {
			console.log("createSection", values);
			const section = await create.mutateAsync({
				data: {
					title: values?.title,
					type: PostType.SECTION,
					parentId: courseId,
				},
			});
			return section;
		},
		[create]
	);

	return { updateSection, createSection, softDeleteById };
};

const updateLecture = (values: Partial<LectureData>): Promise<LectureData> => {
	console.log("updateLecture", values);
	return Promise.resolve({ id: "1", title: values.title || "" });
};

const createLecture = (values: Partial<LectureData>): Promise<LectureData> => {
	console.log("createLecture", values);
	return Promise.resolve({ id: "1", title: values.title || "" });
};

const CourseContentFormHeader = () => (
	<Alert
		type="info"
		message="创建您的课程大纲"
		description={
			<>
				<p>通过组织清晰的章节和课时,帮助学员更好地学习。建议:</p>
				<ul className="mt-2 list-disc list-inside">
					<li>将相关内容组织到章节中</li>
					<li>每个章节建议包含 3-7 个课时</li>
					<li>课时可以是视频、文章或测验</li>
				</ul>
			</>
		}
		className="mb-8"
	/>
);

const CourseSectionEmpty = () => (
	<div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed">
		<div className="text-gray-500">
			<PlusOutlined className="text-4xl mb-4" />
			<h3 className="text-lg font-medium mb-2">开始创建您的课程内容</h3>
			<p className="text-sm">点击下方按钮添加第一个章节</p>
		</div>
	</div>
);

interface SortableSectionProps {
	id: string;
	courseId?: string;
	field: SectionData;
	remove: () => void;
	children: React.ReactNode;
}

const SortableSection: React.FC<SortableSectionProps> = ({
	id,
	field,
	remove,
	courseId,
	children,
}) => {
	const {
		attributes,
		listeners,
		setNodeRef,
		transform,
		transition,
		isDragging,
	} = useSortable({ id });

	const [form] = Form.useForm();
	const [editing, setEditing] = useState(field.id ? false : true);
	const [loading, setLoading] = useState(false);
	const { createSection, updateSection } = useCourseActions();
	const handleSave = async () => {
		if (!courseId) {
			toast.error("课程未创建，请先填写课程基本信息完成创建");
			return;
		}
		try {
			setLoading(true);
			const values = await form.validateFields();
			const result = field.id
				? await updateSection(values)
				: await createSection(values, courseId);
			field.id = result.id;
			setEditing(false);
			message.success("保存成功");
		} catch (error) {
			console.log(error);
			message.error("保存失败");
		} finally {
			setLoading(false);
		}
	};

	const style = {
		transform: CSS.Transform.toString(transform),
		transition,
		backgroundColor: isDragging ? "#f5f5f5" : undefined,
	};

	return (
		<div ref={setNodeRef} style={style} className="mb-4">
			<Collapse>
				<Collapse.Panel
					header={
						editing ? (
							<Form
								form={form}
								className="flex items-center gap-4">
								<Form.Item
									name="title"
									className="mb-0 flex-1"
									initialValue={field?.title}>
									<Input placeholder="章节标题" />
								</Form.Item>
								<Space>
									<Button
										onClick={handleSave}
										loading={loading}
										icon={<SaveOutlined />}
										type="primary">
										保存
									</Button>
									<Button
										onClick={() => {
											setEditing(false);
											if (!id) {
												remove();
											}
										}}>
										取消
									</Button>
								</Space>
							</Form>
						) : (
							<div className="flex items-center justify-between">
								<Space>
									<DragOutlined
										{...attributes}
										{...listeners}
										className="cursor-move"
									/>
									<span>{field.title || "未命名章节"}</span>
								</Space>
								<Space>
									<Button
										type="link"
										onClick={() => setEditing(true)}>
										编辑
									</Button>
									<Button type="link" danger onClick={remove}>
										删除
									</Button>
								</Space>
							</div>
						)
					}
					key={field.id || "new"}>
					{children}
				</Collapse.Panel>
			</Collapse>
		</div>
	);
};

interface SortableLectureProps {
	field: LectureData;
	remove: () => void;
	sectionFieldKey: string;
}

const SortableLecture: React.FC<SortableLectureProps> = ({
	field,
	remove,
	sectionFieldKey,
}) => {
	const {
		attributes,
		listeners,
		setNodeRef,
		transform,
		transition,
		isDragging,
	} = useSortable({ id: field?.id });
	const { create, update } = usePost();
	const [form] = Form.useForm();
	const [editing, setEditing] = useState(field?.id ? false : true);
	const [loading, setLoading] = useState(false);
	const lectureType = Form.useWatch("type", form) || LectureType.ARTICLE;
	const handleSave = async () => {
		try {
			setLoading(true);
			const values = await form.validateFields();
			let result;
			try {
				if (!field.id) {
					result = await create.mutateAsync({
						data: {
							parentId: sectionFieldKey,
							type: PostType.LECTURE,
							title: values?.title,
							meta: {
								type: values?.type,
							},
							resources: {
								connect: (values?.resourceIds || []).map(
									(fileId) => ({
										fileId,
									})
								),
							},
							content: values?.content,
						},
					});
				} else {
					result = await update.mutateAsync({
						where: {
							id: field?.id,
						},
						data: {
							title: values?.title,
							meta: {
								type: values?.type,
							},
							resources: {
								connect: (values?.resourceIds || []).map(
									(fileId) => ({
										fileId,
									})
								),
							},
							content: values?.content,
						},
					});
				}
			} catch (err) {
				console.log(err);
			}

			field.id = result.id;
			setEditing(false);
			message.success("保存成功");
		} catch (error) {
			message.error("保存失败");
		} finally {
			setLoading(false);
		}
	};

	const style = {
		transform: CSS.Transform.toString(transform),
		transition,
		borderBottom: "1px solid #f0f0f0",
		backgroundColor: isDragging ? "#f5f5f5" : undefined,
	};

	return (
		<div ref={setNodeRef} style={style} className="p-4">
			{editing ? (
				<Form form={form} initialValues={field}>
					<div className="flex gap-4">
						<Form.Item
							name="title"
							initialValue={field?.title}
							className="mb-0 flex-1"
							rules={[{ required: true }]}>
							<Input placeholder="课时标题" />
						</Form.Item>
						<Form.Item
							name="type"
							className="mb-0 w-32"
							initialValue={LectureType.ARTICLE}
							rules={[{ required: true }]}>
							<Select
								placeholder="选择类型"
								options={[
									{ label: "视频", value: LectureType.VIDEO },
									{
										label: "文章",
										value: LectureType.ARTICLE,
									},
								]}
							/>
						</Form.Item>
					</div>
					<div className="mt-4 flex flex-1 ">
						{lectureType === LectureType.VIDEO ? (
							<Form.Item
								name="resourceIds"
								className="mb-0 flex-1"
								rules={[{ required: true }]}>
								<TusUploader />
							</Form.Item>
						) : (
							<Form.Item
								name="content"
								className="mb-0 flex-1"
								rules={[{ required: true }]}>
								<QuillEditor />
							</Form.Item>
						)}
					</div>

					<div className="mt-4 flex justify-end gap-2">
						<Button
							onClick={handleSave}
							loading={loading}
							type="primary"
							icon={<SaveOutlined />}>
							保存
						</Button>
						<Button
							onClick={() => {
								setEditing(false);
								if (!field?.id) {
									remove();
								}
							}}>
							取消
						</Button>
					</div>
				</Form>
			) : (
				<div className="flex items-center justify-between">
					<Space>
						<DragOutlined
							{...attributes}
							{...listeners}
							className="cursor-move"
						/>
						<CaretRightOutlined />
						<span>{field?.title || "未命名课时"}</span>
					</Space>
					<Space>
						<Button type="link" onClick={() => setEditing(true)}>
							编辑
						</Button>
						<Button type="link" danger onClick={remove}>
							删除
						</Button>
					</Space>
				</div>
			)}
		</div>
	);
};

interface LectureListProps {
	field: SectionData;
	sectionId: string;
}

const LectureList: React.FC<LectureListProps> = ({ field, sectionId }) => {
	const { softDeleteByIds } = usePost();
	const { data: lectures = [], isLoading } = (
		api.post.findMany as any
	).useQuery(
		{
			where: {
				parentId: sectionId,
				type: PostType.LECTURE,
				deletedAt: null,
			},
		},
		{
			enabled: !!sectionId,
		}
	);
	useEffect(() => {
		if (lectures && !isLoading) {
			setItems(lectures);
		}
	}, [lectures, isLoading]);
	const [items, setItems] = useState<LectureData[]>(lectures);

	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates,
		})
	);

	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;
		if (!over || active.id === over.id) return;

		setItems((items) => {
			const oldIndex = items.findIndex((item) => item.id === active.id);
			const newIndex = items.findIndex((item) => item.id === over.id);
			return arrayMove(items, oldIndex, newIndex);
		});
	};

	return (
		<div className="pl-8">
			<div
				onClick={() => {
					console.log(lectures);
				}}>
				123
			</div>
			<DndContext
				sensors={sensors}
				collisionDetection={closestCenter}
				onDragEnd={handleDragEnd}>
				<SortableContext
					items={items}
					strategy={verticalListSortingStrategy}>
					{items.map((lecture) => (
						<SortableLecture
							key={lecture.id}
							field={lecture}
							remove={async () => {
								if (lecture?.id) {
									await softDeleteByIds.mutateAsync({
										ids: [lecture.id],
									});
								}
								setItems(lectures);
							}}
							sectionFieldKey={sectionId}
						/>
					))}
				</SortableContext>
			</DndContext>
			<Button
				type="dashed"
				block
				icon={<PlusOutlined />}
				className="mt-4"
				onClick={() => {
					setItems([
						...items.filter((item) => !!item.id),
						{ id: null, title: "" },
					]);
				}}>
				添加课时
			</Button>
		</div>
	);
};

const CourseContentForm: React.FC = () => {
	const { editId } = useCourseEditor();
	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates,
		})
	);
	const { softDeleteByIds } = usePost();
	const { data: sections = [], isLoading } = api.post.findMany.useQuery(
		{
			where: {
				parentId: editId,
				type: PostType.SECTION,
				deletedAt: null,
			},
		},
		{
			enabled: !!editId,
		}
	);

	const [items, setItems] = useState<any[]>(sections);
	useEffect(() => {
		if (sections && !isLoading) {
			setItems(sections);
		}
	}, [sections]);
	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;
		if (!over || active.id === over.id) return;

		setItems((items) => {
			const oldIndex = items.findIndex((item) => item.id === active.id);
			const newIndex = items.findIndex((item) => item.id === over.id);
			return arrayMove(items, oldIndex, newIndex);
		});
	};

	return (
		<div className="max-w-4xl mx-auto p-6">
			<CourseContentFormHeader />

			{items.length === 0 ? (
				<CourseSectionEmpty />
			) : (
				<DndContext
					sensors={sensors}
					collisionDetection={closestCenter}
					onDragEnd={handleDragEnd}>
					<SortableContext
						items={items}
						strategy={verticalListSortingStrategy}>
						{items.map((section, index) => (
							<SortableSection
								courseId={editId}
								key={section.id}
								id={section.id}
								field={section}
								remove={async () => {
									if (section?.id) {
										await softDeleteByIds.mutateAsync({
											ids: [section.id],
										});
									}
									setItems(sections);
								}}>
								<LectureList
									field={section}
									sectionId={section.id}
								/>
							</SortableSection>
						))}
					</SortableContext>
				</DndContext>
			)}

			<Button
				type="dashed"
				block
				icon={<PlusOutlined />}
				className="mt-4"
				onClick={() => {
					setItems([
						...items.filter((item) => !!item.id),
						{ id: null, title: "" },
					]);
				}}>
				添加章节
			</Button>
		</div>
	);
};

export default CourseContentForm;
