import { PlusOutlined } from "@ant-design/icons";
import { Button } from "antd";
import React, { useEffect, useState } from "react";
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
	DragEndEvent,
} from "@dnd-kit/core";
import { api } from "@nice/client";
import {
	arrayMove,
	SortableContext,
	sortableKeyboardCoordinates,
	verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { PostType } from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import { CourseContentFormHeader } from "./CourseContentFormHeader";
import { CourseSectionEmpty } from "./CourseSectionEmpty";
import { SortableSection } from "./SortableSection";
import { LectureList } from "./LectureList";
import toast from "react-hot-toast";
import { useQueryClient } from "@tanstack/react-query";
import { getQueryKey } from "@trpc/react-query";

const CourseContentForm: React.FC = () => {
	const queryClient = useQueryClient();
	const { editId } = useCourseEditor();
	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates,
		})
	);
	const { softDeleteByIds, updateOrderByIds } = usePost();
	const { data: sections = [], isLoading } = api.post.findMany.useQuery(
		{
			where: {
				parentId: editId,
				type: PostType.SECTION,
				deletedAt: null,
			},
			orderBy: {
				order: "asc",
			},
		},
		{
			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;
		let newItems = [];
		setItems((items) => {
			const oldIndex = items.findIndex((item) => item.id === active.id);
			const newIndex = items.findIndex((item) => item.id === over.id);
			newItems = arrayMove(items, oldIndex, newIndex);
			return newItems;
		});
		updateOrderByIds.mutateAsync({
			ids: newItems.map((item) => item.id),
		});
	};
	const softDeletePostDescendant = api.post.softDeletePostDescendant.useMutation({
		onSuccess:()=>{
			queryClient.invalidateQueries({ queryKey: getQueryKey(api.post) });
		}
	})
	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}
								field={section}
								remove={async () => {
									if (section?.id) {
										await softDeletePostDescendant.mutateAsync({
											ancestorId: section.id,
										});
									}
									setItems(sections);
								}}>
								<LectureList
									field={section}
									sectionId={section.id}
								/>
							</SortableSection>
						))}
					</SortableContext>
				</DndContext>
			)}

			<Button
				type="dashed"
				block
				icon={<PlusOutlined />}
				className="mt-4"
				onClick={() => {
					if (items.some((item) => item.id === null)) {
						toast.error("请先保存当前编辑的章节");
					} else {
						setItems([...items, { id: null, title: "" }]);
					}
				}}>
				添加章节
			</Button>
		</div>
	);
};

export default CourseContentForm;
