import React, { useEffect, useRef, useState } from "react";
import Quill from "quill";
import "quill/dist/quill.snow.css"; // 引入默认样式
import QuillCharCounter from "./QuillCharCounter";
import { defaultModules } from "./constants";

interface QuillEditorProps {
	value?: string;
	onChange?: (content: string) => void;
	placeholder?: string;
	readOnly?: boolean;
	theme?: "snow" | "bubble";
	modules?: any;
	className?: string;
	style?: React.CSSProperties;
	onFocus?: () => void;
	onBlur?: () => void;
	onKeyDown?: (event: KeyboardEvent) => void;
	onKeyUp?: (event: KeyboardEvent) => void;
	maxLength?: number;
	minLength?: number;
	minRows?: number;
	maxRows?: number;
}
const QuillEditor: React.FC<QuillEditorProps> = ({
	value = "",
	onChange,
	placeholder = "请输入内容...",
	readOnly = false,
	theme = "snow",
	modules = defaultModules,
	className = "",
	style = {},
	onFocus,
	onBlur,
	onKeyDown,
	onKeyUp,
	maxLength,
	minLength = 0,
	minRows = 1,
	maxRows,
}) => {
	const editorRef = useRef<HTMLDivElement>(null);
	const quillRef = useRef<Quill | null>(null);
	const isMounted = useRef(false);
	const [charCount, setCharCount] = useState(0); // 添加字符计数状态
	const handleTextChange = () => {
		if (!quillRef.current) return;
		const editor = quillRef.current;
		// 获取文本并处理换行符
		const text = editor.getText().replace(/\n$/, "");
		const textLength = text.length;

		// 处理最大长度限制
		if (maxLength && textLength > maxLength) {
			// 暂时移除事件监听器
			editor.off("text-change", handleTextChange);

			// 获取当前选区
			const selection = editor.getSelection();
			const delta = editor.getContents();
			let length = 0;
			const newDelta = delta.ops?.reduce((acc: any, op: any) => {
				if (typeof op.insert === "string") {
					const remainingLength = maxLength - length;
					if (length < maxLength) {
						const truncatedText = op.insert.slice(
							0,
							remainingLength
						);
						length += truncatedText.length;
						acc.push({ ...op, insert: truncatedText });
					}
				} else {
					acc.push(op);
				}
				return acc;
			}, []);
			// 更新内容
			editor.setContents({ ops: newDelta } as any);
			// 恢复光标位置
			if (selection) {
				editor.setSelection(Math.min(selection.index, maxLength));
			}
			// 重新计算截断后的实际长度
			const finalText = editor.getText().replace(/\n$/, "");
			setCharCount(finalText.length);

			// 重新绑定事件监听器
			editor.on("text-change", handleTextChange);
		} else {
			// 如果没有超出最大长度，直接更新字符计数
			setCharCount(textLength);
		}

		onChange?.(quillRef.current.root.innerHTML);
	};

	useEffect(() => {
		if (!editorRef.current) return;
		if (!isMounted.current) {
			// 初始化 Quill 编辑器
			quillRef.current = new Quill(editorRef.current, {
				theme,
				modules,
				placeholder,
				readOnly,
			});
			// 设置初始内容
			quillRef.current.root.innerHTML = value;
			if (onFocus) {
				quillRef.current.on(Quill.events.SELECTION_CHANGE, (range) => {
					if (range) {
						onFocus();
					}
				});
			}
			if (onBlur) {
				quillRef.current.on(Quill.events.SELECTION_CHANGE, (range) => {
					if (!range) {
						onBlur();
					}
				});
			}
			quillRef.current.on(Quill.events.TEXT_CHANGE, handleTextChange);
			if (onKeyDown) {
				quillRef.current.root.addEventListener("keydown", onKeyDown);
			}
			if (onKeyUp) {
				quillRef.current.root.addEventListener("keyup", onKeyUp);
			}
			isMounted.current = true;
		}
	}, [
		theme,
		modules,
		placeholder,
		readOnly,
		onFocus,
		onBlur,
		onKeyDown,
		onKeyUp,
		maxLength,
		minLength,
	]); // 添加所有相关的依赖
	useEffect(() => {
		if (quillRef.current) {
			const editor = editorRef.current?.querySelector(
				".ql-editor"
			) as HTMLElement;
			if (editor) {
				const lineHeight = parseInt(
					window.getComputedStyle(editor).lineHeight,
					10
				);
				const paddingTop = parseInt(
					window.getComputedStyle(editor).paddingTop,
					10
				);
				const paddingBottom = parseInt(
					window.getComputedStyle(editor).paddingBottom,
					10
				);
				const minHeight =
					lineHeight * minRows + paddingTop + paddingBottom;
				editor.style.minHeight = `${minHeight}px`;
				if (maxRows) {
					const maxHeight =
						lineHeight * maxRows + paddingTop + paddingBottom;
					editor.style.maxHeight = `${maxHeight}px`;
					editor.style.overflowY = "auto";
				}
			}
		}
	}, [minRows, maxRows, quillRef.current]);

	// 监听 value 属性变化
	useEffect(() => {
		if (quillRef.current && value !== quillRef.current.root.innerHTML) {
			quillRef.current.root.innerHTML = value;
		}
	}, [value]);

	return (
		<div className={`quill-editor-container ${className}`} style={style}>
			<div ref={editorRef} />
			{(maxLength || minLength > 0) && (
				<QuillCharCounter
					currentCount={charCount}
					maxLength={maxLength}
					minLength={minLength}
				/>
			)}
		</div>
	);
};

export default QuillEditor;
