import {
	PlusOutlined,
	DragOutlined,
	DeleteOutlined,
	CaretRightOutlined,
	SaveOutlined,
} from "@ant-design/icons";
import { Form, Alert, Button, Input, Select, Space, Collapse, message } from "antd";
import React, { useState } from "react";
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
} from "@dnd-kit/core";
import { usePost } 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 { LectureType } from "@nice/common";
import { useCourseEditor } from "../context/CourseEditorContext";

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>
);

const SortableSection = ({ id, field, remove, children }: any) => {
	const { attributes, listeners, setNodeRef, transform, transition } =
		useSortable({ id });
	const [form] = Form.useForm();
	const { update, create } = usePost();
	const [loading, setLoading] = useState(false);

	const style = {
		transform: CSS.Transform.toString(transform),
		transition,
	};

	const handleSave = async () => {
		try {
			const values = await form.validateFields();
			setLoading(true);
			
			if (values.id) {
				// await update({ ...values, type: 'section' });
				message.success('章节更新成功');
			} else {
				// await create({ ...values, type: 'section' });
				message.success('章节创建成功');
			}
		} catch (error: any) {
			message.error(error.message || '保存失败');
		} finally {
			setLoading(false);
		}
	};

	const items = [
		{
			key: field.name,
			label: (
				<Form
					form={form}
					initialValues={field.value}>
					<div className="flex items-center justify-between flex-1">
						<Form.Item
							name="title"
							rules={[{ required: true, message: "请输入章节标题" }]}
							className="mb-0 flex-1 mr-4">
							<Input placeholder="输入章节标题" />
						</Form.Item>
						<div className="flex items-center gap-2">
							<Button
								type="primary"
								icon={<SaveOutlined />}
								loading={loading}
								onClick={handleSave}>
								保存
							</Button>
							<span
								{...listeners}
								{...attributes}
								className="cursor-move">
								<DragOutlined className="text-gray-400 hover:text-gray-600" />
							</span>
							<DeleteOutlined
								onClick={() => remove(field.name)}
								className="text-red-500 cursor-pointer"
							/>
						</div>
					</div>
				</Form>
			),
			children: <div className="mt-4">{children}</div>,
		},
	];

	return (
		<div ref={setNodeRef} style={style} className="mb-4">
			<Collapse
				items={items}
				defaultActiveKey={[field.name]}
				expandIcon={({ isActive }) => (
					<CaretRightOutlined rotate={isActive ? 90 : 0} />
				)}
				className="bg-gray-50"
			/>
		</div>
	);
};

const SortableLecture = ({ id, field, remove, sectionId }: any) => {
	const { attributes, listeners, setNodeRef, transform, transition } =
		useSortable({ id });

	const style = {
		transform: CSS.Transform.toString(transform),
		transition,
	};

	const { form, taxonomies } = useCourseEditor();
	const lectureType =
		Form.useWatch(
			["sections", sectionId, "lectures", field.name, "type"],
			form
		) || LectureType.VIDEO;

	const renderLabel = () => (
		<div className="flex items-center justify-between w-full">
			<Form.Item
				{...field}
				name={[field.name, "title"]}
				rules={[{ required: true, message: "请输入课时标题" }]}
				className="mb-0 flex-1 mr-4">
				<Input placeholder="输入课时标题" />
			</Form.Item>
			<Form.Item
				{...field}
				name={[field.name, "type"]}
				rules={[{ required: true }]}
				initialValue={LectureType.VIDEO}
				className="mb-0 w-32">
				<Select
					options={[
						{ label: "视频", value: LectureType.VIDEO },
						{ label: "文章", value: LectureType.ARTICLE },
					]}
				/>
			</Form.Item>
			<div className="flex items-center">
				<DeleteOutlined
					onClick={() => remove(field.name)}
					className="text-red-500 cursor-pointer mx-2"
				/>
				<span {...listeners} {...attributes} className="cursor-move">
					<DragOutlined className="text-gray-400 hover:text-gray-600" />
				</span>
			</div>
		</div>
	);

	const renderContent = () => (
		<div className="mt-4">
			{lectureType === LectureType.ARTICLE && (
				<Form.Item
					{...field}
					name={[field.name, "content"]}
					rules={[{ required: true, message: "请输入文章内容" }]}>
					<QuillEditor />
				</Form.Item>
			)}

			{lectureType === LectureType.VIDEO && (
				<Form.Item
					{...field}
					name={[field.name, "resourceIds"]}
					rules={[{ required: true, message: "请上传视频" }]}>
					<TusUploader />
				</Form.Item>
			)}
		</div>
	);

	return (
		<div ref={setNodeRef} style={style} className="mb-4">
			<Collapse
				defaultActiveKey={[field.key]}
				expandIcon={({ isActive }) => (
					<CaretRightOutlined rotate={isActive ? 90 : 0} />
				)}
				className="bg-white shadow-sm border">
				<Collapse.Panel key={field.key} header={renderLabel()}>
					{renderContent()}
				</Collapse.Panel>
			</Collapse>
		</div>
	);
};

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

	return (
		<Form.List name={[field.name, "lectures"]}>
			{(fields, { add, remove, move }) => (
				<>
					<DndContext
						sensors={sensors}
						collisionDetection={closestCenter}
						onDragEnd={({ active, over }) => {
							if (over && active.id !== over.id) {
								const oldIndex = fields.findIndex(
									(field) => field.key === active.id
								);
								const newIndex = fields.findIndex(
									(field) => field.key === over.id
								);
								if (oldIndex !== -1 && newIndex !== -1) {
									move(oldIndex, newIndex);
								}
							}
						}}>
						<SortableContext
							items={fields.map((f) => f.key)}
							strategy={verticalListSortingStrategy}>
							{fields.map((lectureField) => (
								<SortableLecture
									key={lectureField.key}
									id={lectureField.key}
									field={lectureField}
									sectionId={field.name}
									remove={remove}
								/>
							))}
						</SortableContext>
					</DndContext>
					<Button
						type="dashed"
						onClick={() => add({ type: LectureType.VIDEO })}
						block
						icon={<PlusOutlined />}>
						添加课时
					</Button>
				</>
			)}
		</Form.List>
	);
};

export default function CourseContentForm() {
	const { form, taxonomies } = useCourseEditor();
	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates,
		})
	);

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

			<Form.List name="sections">
				{(fields, { add, remove, move }) => (
					<DndContext
						sensors={sensors}
						collisionDetection={closestCenter}
						onDragEnd={({ active, over }) => {
							if (over && active.id !== over.id) {
								const oldIndex = fields.findIndex(
									(field) => field.key === active.id
								);
								const newIndex = fields.findIndex(
									(field) => field.key === over.id
								);
								if (oldIndex !== -1 && newIndex !== -1) {
									move(oldIndex, newIndex);
								}
							}
						}}>
						<SortableContext
							items={fields.map((f) => f.key)}
							strategy={verticalListSortingStrategy}>
							{fields.length === 0 && <CourseSectionEmpty />}
							{fields.map((field) => (
								<SortableSection
									key={field.key}
									id={field.key}
									field={field}
									remove={remove}>
									<LectureList field={field} />
								</SortableSection>
							))}
						</SortableContext>
						<Form.Item>
							<Button
								block
								size="large"
								onClick={() =>
									add({ title: "新章节", lectures: [] })
								}
								icon={<PlusOutlined />}
								type="primary"
								className="mt-4">
								添加新章节
							</Button>
						</Form.Item>
					</DndContext>
				)}
			</Form.List>
		</div>
	);
}
