import {
	DragOutlined,
	CaretRightOutlined,
	SaveOutlined,
	CaretDownOutlined,
} from "@ant-design/icons";
import { Form, Button, Input, Select, Space } from "antd";
import React, { useState } from "react";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { TusUploader } from "@web/src/components/common/uploader/TusUploader";
import {
	Lecture,
	LectureType,
	LessonTypeLabel,
	PostType,
	ResourceStatus,
	videoMimeTypes,
} from "@nice/common";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";

import { env } from "@web/src/env";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer";
import MultiAvatarUploader from "@web/src/components/common/uploader/MultiAvatarUploader";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
import { set } from "idb-keyval";

interface SortableLectureProps {
	field: Lecture;
	remove: () => void;
	sectionFieldKey: string;
}
export 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 [isContentVisible, setIsContentVisible] = useState(false); // State to manage content visibility

	const handleToggleContent = () => {
		setIsContentVisible(!isContentVisible); // Toggle content visibility
	};
	const lectureType =
		Form.useWatch(["meta", "type"], form) || LectureType.ARTICLE;
	const handleSave = async () => {
		try {
			setLoading(true);
			const values = await form.validateFields();
			let result;
			const fileIds = values?.meta?.fileIds || [];
			const videoUrlId = Array.isArray(values?.meta?.videoIds)
				? values?.meta?.videoIds[0]
				: typeof values?.meta?.videoIds === "string"
					? values?.meta?.videoIds
					: undefined;
			console.log(sectionFieldKey);
			if (!field.id) {
				result = await create.mutateAsync({
					data: {
						parentId: sectionFieldKey,
						type: PostType.LECTURE,
						title: values?.title,
						meta: {
							type: values?.meta?.type,
							fileIds: fileIds,
							videoIds: videoUrlId ? [videoUrlId] : [],
							videoUrl: videoUrlId
								? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
								: undefined,
						},
						resources:
							[videoUrlId, ...fileIds].filter(Boolean)?.length > 0
								? {
										connect: [videoUrlId, ...fileIds]
											.filter(Boolean)
											.map((fileId) => ({
												fileId,
											})),
									}
								: undefined,
						content: values?.content,
					},
				});
			} else {
				result = await update.mutateAsync({
					where: {
						id: field?.id,
					},
					data: {
						parentId: sectionFieldKey,
						title: values?.title,
						meta: {
							type: values?.meta?.type,
							fileIds: fileIds,
							videoIds: videoUrlId ? [videoUrlId] : [],
							videoUrl: videoUrlId
								? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
								: undefined,
						},
						resources:
							[videoUrlId, ...fileIds].filter(Boolean)?.length > 0
								? {
										set: [videoUrlId, ...fileIds]
											.filter(Boolean)
											.map((fileId) => ({
												fileId,
											})),
									}
								: undefined,
						content: values?.content,
					},
				});
			}
			setIsContentVisible(false);
			toast.success("课时已更新");
			field.id = result.id;
			setEditing(false);
		} catch (err) {
			toast.success("更新失败");
			console.log(err);
		} 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, message: "请输入课时标题" },
							]}>
							<Input placeholder="课时标题" />
						</Form.Item>
						<Form.Item
							name={["meta", "type"]}
							className="mb-0 w-32"
							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={["meta", "videoIds"]}
								className="mb-0 flex-1"
								rules={[
									{
										required: true,
										message: "请传入视频",
									},
								]}>
								<TusUploader
									allowTypes={videoMimeTypes}
									multiple={false}
								/>
							</Form.Item>
						) : (
							<div>
								<Form.Item
									name="content"
									className="mb-0 flex-1"
									rules={[
										{
											required: true,
											message: "请输入内容",
										},
									]}>
									<QuillEditor />
								</Form.Item>
								<Form.Item
									name={["meta", "fileIds"]}
									className="mb-0 flex-1">
									<TusUploader multiple={true} />
								</Form.Item>
							</div>
						)}
					</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"
						/>
						{isContentVisible ? (
							<CaretDownOutlined onClick={handleToggleContent} />
						) : (
							<CaretRightOutlined onClick={handleToggleContent} />
						)}
						<span>{LessonTypeLabel[field?.meta?.type]}</span>
						<span>{field?.title || "未命名课时"}</span>
					</Space>
					<Space>
						<Button type="link" onClick={() => setEditing(true)}>
							编辑
						</Button>
						<Button type="link" danger onClick={remove}>
							删除
						</Button>
					</Space>
				</div>
			)}
			{isContentVisible &&
				!editing && // Conditionally render content based on type
				(field?.meta?.type === LectureType.ARTICLE ? (
					<div>
						<CollapsibleContent
							maxHeight={200}
							content={field?.content}
						/>
						<div className="px-6 ">
							<ResourcesShower
								resources={field?.resources}></ResourcesShower>
						</div>
					</div>
				) : (
					<VideoPlayer src={field?.meta?.videoUrl} />
				))}
		</div>
	);
};
