import {
	PlusOutlined,
	DragOutlined,
	DeleteOutlined,
	CaretRightOutlined,
	SaveOutlined,
} from "@ant-design/icons";
import {
	Form,
	Alert,
	Button,
	Input,
	Select,
	Space,
	Collapse,
	message,
} from "antd";
import React, { 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 {
	Lecture,
	lectureDetailSelect,
	LectureType,
	PostType,
} from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import { LectureData, SectionData } from "./interface";
import { SortableLecture } from "./SortableLecture";
import toast from "react-hot-toast";

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

export const LectureList: React.FC<LectureListProps> = ({
	field,
	sectionId,
}) => {
	const { softDeleteByIds, updateOrderByIds } = usePost();
	const { data: lectures = [], isLoading } = (
		api.post.findMany as any
	).useQuery(
		{
			where: {
				parentId: sectionId,
				type: PostType.LECTURE,
				deletedAt: null,
			},
			orderBy: {
				order: "asc",
			},
			select: lectureDetailSelect,
		},
		{
			enabled: !!sectionId,
		}
	);

	// 用 lectures 初始化 items 状态
	const [items, setItems] = useState<Lecture[]>(lectures);

	// 当 lectures 变化时更新 items
	useEffect(() => {
		if (!isLoading) {
			setItems(lectures);
		}
	}, [lectures, isLoading]);

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

	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;
		if (!over || active.id === over.id) return;
		// updateOrder.mutateAsync({
		// 	id: active.id,
		// 	overId: over.id,
		// });
		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),
		});
	};

	return (
		<div className="pl-8">
			<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={() => {
					if (items.some((item) => item.id === null)) {
						toast.error("请先保存当前编辑中的课时！");
					} else {
						setItems((prevItems) => [
							...prevItems.filter((item) => !!item.id),
							{
								id: null,
								title: "",
								meta: {
									type: LectureType.ARTICLE,
								},
							} as Lecture,
						]);
					}
				}}>
				添加课时
			</Button>
		</div>
	);
};
