import React, { useState, useRef, useCallback } from 'react';
import './AIPanel.css';

interface AIPanelProps {
	height: number;
	onHeightChange: (height: number) => void;
	maximized: boolean;
	onMaximizeChange: (maximized: boolean) => void;
}

const AIPanel: React.FC<AIPanelProps> = ({
	height,
	onHeightChange,
	maximized,
	onMaximizeChange,
}) => {
	const [isMinimized, setIsMinimized] = useState(false);
	const [messages, setMessages] = useState<{ role: 'user' | 'ai'; content: string }[]>([
		{ role: 'ai', content: '你好！我是 AI 助手，可以帮助你生成意图编制内容、检查内容完整性等。有什么需要帮助的吗？' },
	]);
	const [input, setInput] = useState('');
	const [isLoading, setIsLoading] = useState(false);
	const panelRef = useRef<HTMLDivElement>(null);
	const resizeRef = useRef<HTMLDivElement>(null);

	// 拖拽调整大小
	const handleMouseDown = useCallback((e: React.MouseEvent) => {
		e.preventDefault();
		const startY = e.clientY;
		const startHeight = height;

		const handleMouseMove = (e: MouseEvent) => {
			const delta = startY - e.clientY;
			const newHeight = Math.max(150, Math.min(600, startHeight + delta));
			onHeightChange(newHeight);
		};

		const handleMouseUp = () => {
			document.removeEventListener('mousemove', handleMouseMove);
			document.removeEventListener('mouseup', handleMouseUp);
		};

		document.addEventListener('mousemove', handleMouseMove);
		document.addEventListener('mouseup', handleMouseUp);
	}, [height, onHeightChange]);

	// 发送消息
	const handleSend = async () => {
		if (!input.trim() || isLoading) return;

		const userMessage = input.trim();
		setMessages(prev => [...prev, { role: 'user', content: userMessage }]);
		setInput('');
		setIsLoading(true);

		try {
			const response = await fetch('http://localhost:8080/api/ai/generate', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ prompt: userMessage }),
			});
			const data = await response.json();

			if (data.success) {
				setMessages(prev => [...prev, { role: 'ai', content: data.content }]);
			} else {
				setMessages(prev => [...prev, { role: 'ai', content: `错误: ${data.error || '请求失败'}` }]);
			}
		} catch (error) {
			setMessages(prev => [...prev, { role: 'ai', content: '网络错误，请确保后端服务已启动。' }]);
		} finally {
			setIsLoading(false);
		}
	};

	const handleKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			handleSend();
		}
	};

	// 切换最小化
	const toggleMinimize = () => {
		if (maximized) {
			onMaximizeChange(false);
		}
		setIsMinimized(!isMinimized);
	};

	// 切换最大化
	const toggleMaximize = () => {
		if (isMinimized) {
			setIsMinimized(false);
		}
		onMaximizeChange(!maximized);
	};

	const panelHeight = maximized ? '100%' : isMinimized ? 36 : height;

	return (
		<div
			ref={panelRef}
			className={`ai-panel ${maximized ? 'maximized' : ''} ${isMinimized ? 'minimized' : ''}`}
			style={{ height: panelHeight }}
		>
			{/* 拖拽条 */}
			{!maximized && !isMinimized && (
				<div
					ref={resizeRef}
					className="resize-handle"
					onMouseDown={handleMouseDown}
				/>
			)}

			{/* 标题栏 */}
			<div className="ai-panel-header">
				<span className="ai-panel-title">AI 交互窗口</span>
				<div className="ai-panel-controls">
					<button
						className="panel-control-btn"
						onClick={toggleMinimize}
						title={isMinimized ? '展开' : '最小化'}
					>
						<svg viewBox="0 0 16 16" width="14" height="14">
							{isMinimized ? (
								<path d="M3 8h10M8 3v10" stroke="currentColor" strokeWidth="1.5" fill="none" />
							) : (
								<rect x="3" y="7" width="10" height="2" fill="currentColor" />
							)}
						</svg>
					</button>
					<button
						className="panel-control-btn"
						onClick={toggleMaximize}
						title={maximized ? '还原' : '最大化'}
					>
						<svg viewBox="0 0 16 16" width="14" height="14">
							{maximized ? (
								<>
									<rect x="3" y="5" width="8" height="8" stroke="currentColor" strokeWidth="1.5" fill="none" />
									<path d="M5 5V3h8v8h-2" stroke="currentColor" strokeWidth="1.5" fill="none" />
								</>
							) : (
								<rect x="3" y="3" width="10" height="10" stroke="currentColor" strokeWidth="1.5" fill="none" />
							)}
						</svg>
					</button>
				</div>
			</div>

			{/* 内容区 */}
			{!isMinimized && (
				<div className="ai-panel-content">
					<div className="ai-messages">
						{messages.map((msg, idx) => (
							<div key={idx} className={`ai-message ${msg.role}`}>
								<div className="message-avatar">
									{msg.role === 'ai' ? '🤖' : '👤'}
								</div>
								<div className="message-content selectable">
									{msg.content}
								</div>
							</div>
						))}
						{isLoading && (
							<div className="ai-message ai">
								<div className="message-avatar">🤖</div>
								<div className="message-content loading">
									<span className="loading-dot"></span>
									<span className="loading-dot"></span>
									<span className="loading-dot"></span>
								</div>
							</div>
						)}
					</div>
					<div className="ai-input-area">
						<textarea
							className="ai-input selectable"
							placeholder="输入消息，按 Enter 发送..."
							value={input}
							onChange={(e) => setInput(e.target.value)}
							onKeyDown={handleKeyDown}
							rows={2}
						/>
						<button
							className="ai-send-btn"
							onClick={handleSend}
							disabled={!input.trim() || isLoading}
						>
							发送
						</button>
					</div>
				</div>
			)}
		</div>
	);
};

export default AIPanel;
