import React, { useContext, useRef, useState } from "react";
import { motion } from "framer-motion";
import { Button, Input, Tabs } from "antd";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { PostDetailContext } from "./context/PostDetailContext";
import { usePost } from "@nice/client";
import { PostType } from "@nice/common";
import toast from "react-hot-toast";
import { isContentEmpty } from "./utils";
import { SendOutlined } from "@ant-design/icons";
import { TusUploader } from "@web/src/components/common/uploader/TusUploader";
import { CustomAvatar } from "@web/src/components/presentation/CustomAvatar";

const { TabPane } = Tabs;

export default function PostCommentEditor() {
	const { post } = useContext(PostDetailContext);
	const [content, setContent] = useState("");
	const [signature, setSignature] = useState<string | undefined>(undefined);
	const [fileIds, setFileIds] = useState<string[]>([]);
	const { create } = usePost();
	const [uploaderKey, setUploaderKey] = useState<number>(0);

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		if (isContentEmpty(content)) {
			toast.error("内容不得为空");
			return;
		}

		try {
			await create.mutateAsync({
				data: {
					type: PostType.POST_COMMENT,

					parentId: post?.id,
					content: content,
					resources: {
						connect: fileIds.filter(Boolean).map((id) => ({
							fileId: id,
						})),
					},
					meta: {
						signature,
					},
				},
			});
			toast.success("发布成功！");
			setContent("");
			setFileIds([]); // 重置上传组件状态
			setSignature("");
			setUploaderKey(uploaderKey + 1);
		} catch (error) {
			toast.error("发布失败，请稍后重试");
			console.error("Error posting comment:", error);
		}
		// TODO: 实现提交逻辑
		console.log("Submitting:", content);
		setContent("");
	};

	return (
		<div className="p-6">
			<form onSubmit={handleSubmit} className="space-y-2">
				<Tabs defaultActiveKey="1">
					<TabPane tab="回复" key="1">
						<div className="relative rounded-xl border  border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
							<QuillEditor
								value={content}
								onChange={setContent}
								className="bg-transparent"
								theme="snow"
								minRows={6}
								modules={{
									toolbar: [
										["bold", "italic", "strike"],
										["blockquote", "code-block"],
										[
											{ list: "ordered" },
											{ list: "bullet" },
										],
										["link"],
										["clean"],
									],
								}}
							/>
						</div>
					</TabPane>
					<TabPane tab="附件" key="2">
						<div className="relative rounded-xl border  border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
							<TusUploader
								key={uploaderKey}
								value={fileIds}
								onChange={(value) => {
									setFileIds(value);
								}}
							/>
						</div>
					</TabPane>
				</Tabs>

				{!isContentEmpty(content) && (
					<div className="flex items-center justify-end gap-2">
						<CustomAvatar randomString={signature}></CustomAvatar>
						<Input
							maxLength={15}
							style={{
								width: 150,
							}}
							onChange={(e) => {
								setSignature(e.target.value);
							}}
							// showCount
							placeholder="签名"
						/>
						<div>
							<Button
								type="primary"
								htmlType="submit"
								disabled={isContentEmpty(content)}
								className="flex items-center space-x-2 bg-primary"
								icon={<SendOutlined />}>
								提交
							</Button>
						</div>
					</div>
				)}
			</form>
		</div>
	);
}
