import React, { useEffect, useRef, useState } from 'react';
import { ModuleType } from '../../App';
import './Toolbar.css';

interface KnowledgeBase {
	id: string;
	name: string;
	description?: string;
}

interface ToolbarProps {
	activeModule: ModuleType;
	onActionClick?: (action: string) => void;
	intentActionStatus?: {
		isSaving: boolean;
		isGenerating: boolean;
		isChecking: boolean;
	};
	selectedKnowledgeBase?: string;
	onKnowledgeBaseChange?: (kbId: string) => void;
}

// 模块对应的快捷操作
const moduleActions: Record<ModuleType, { label: string; actions: string[] }> = {
	intent: {
		label: '意图编制',
		actions: ['开始', 'AI 生成', 'AI 检查', '保存', '导出'],
	},
	task: {
		label: '任务规划',
		actions: ['新建任务', '分配资源', '查看进度', '导出报告'],
	},
	simulation: {
		label: '逻辑仿真',
		actions: ['新建仿真', '运行仿真', '查看结果', '参数配置'],
	},
	code: {
		label: '代码生成',
		actions: ['生成代码', '选择模板', '配置参数', '预览'],
	},
	data: {
		label: '数据服务',
		actions: ['数据查询', '数据导入', '数据导出', '数据统计'],
	},
	knowledge: {
		label: '知识库',
		actions: ['搜索知识', '添加知识', '知识分类', '知识图谱'],
	},
};

// 模拟知识库列表（后续可从后端获取）
const knowledgeBases: KnowledgeBase[] = [
	{ id: 'default', name: '默认知识库', description: '系统默认知识库' },
	{ id: 'test-specs', name: '测试规范库', description: '测试标准和规范' },
	{ id: 'device-params', name: '设备参数库', description: '仪器设备参数' },
	{ id: 'historical', name: '历史案例库', description: '历史测试案例' },
];

const Toolbar: React.FC<ToolbarProps> = ({ 
	activeModule, 
	onActionClick, 
	intentActionStatus,
	selectedKnowledgeBase = 'default',
	onKnowledgeBaseChange 
}) => {
	const currentModule = moduleActions[activeModule];
	const [isStartMenuOpen, setIsStartMenuOpen] = useState(false);
	const [isKbMenuOpen, setIsKbMenuOpen] = useState(false);
	const startMenuRef = useRef<HTMLDivElement>(null);
	const kbMenuRef = useRef<HTMLDivElement>(null);

	const selectedKb = knowledgeBases.find(kb => kb.id === selectedKnowledgeBase) || knowledgeBases[0];
	const isActionLoading = (action: string) => {
		if (action === '保存') return intentActionStatus?.isSaving ?? false;
		if (action === 'AI 生成') return intentActionStatus?.isGenerating ?? false;
		if (action === 'AI 检查') return intentActionStatus?.isChecking ?? false;
		return false;
	};

	const getActionLabel = (action: string) => {
		if (action === '保存' && intentActionStatus?.isSaving) return '保存中...';
		if (action === 'AI 生成' && intentActionStatus?.isGenerating) return 'AI 生成中...';
		if (action === 'AI 检查' && intentActionStatus?.isChecking) return 'AI 检查中...';
		return action;
	};

	const renderActionIcon = (action: string) => {
		switch (action) {
			case '新建意图':
			case '开始':
			case '新建任务':
			case '新建仿真':
				return (
					<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
						<polyline points="14 2 14 8 20 8" />
						<line x1="12" y1="18" x2="12" y2="12" />
						<line x1="9" y1="15" x2="15" y2="15" />
					</svg>
				);
			case '保存':
				return (
					<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
						<polyline points="17 21 17 13 7 13 7 21" />
						<polyline points="7 3 7 8 15 8" />
					</svg>
				);
			case 'AI 生成':
				return (
					<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M12 2L2 7l10 5 10-5-10-5z" />
						<path d="M2 17l10 5 10-5" />
						<path d="M2 12l10 5 10-5" />
					</svg>
				);
			case 'AI 检查':
				return (
					<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M9 11l3 3L22 4" />
						<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
					</svg>
				);
			case '导出':
			case '导出报告':
			case '数据导出':
				return (
					<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M12 3v12" />
						<polyline points="8 11 12 15 16 11" />
						<path d="M4 21h16" />
					</svg>
				);
			default:
				return null;
		}
	};

	useEffect(() => {
		const handleClickOutside = (event: MouseEvent) => {
			if (isStartMenuOpen && startMenuRef.current && !startMenuRef.current.contains(event.target as Node)) {
				setIsStartMenuOpen(false);
			}
			if (isKbMenuOpen && kbMenuRef.current && !kbMenuRef.current.contains(event.target as Node)) {
				setIsKbMenuOpen(false);
			}
		};
		document.addEventListener('mousedown', handleClickOutside);
		return () => document.removeEventListener('mousedown', handleClickOutside);
	}, [isStartMenuOpen, isKbMenuOpen]);
	const getActionClassName = (action: string) => {
		if (action === '保存') {
			return 'toolbar-action primary';
		}
		if (action === 'AI 生成' || action === 'AI 检查') {
			return 'toolbar-action ai';
		}
		return 'toolbar-action';
	};

	return (
		<div className="toolbar">
			<div className="toolbar-left">
				<span className="toolbar-label">{currentModule.label}</span>
				<span className="toolbar-separator">|</span>
				{currentModule.actions.map((action, index) => {
					if (action === '开始') {
						return (
							<div key={index} className="toolbar-dropdown" ref={startMenuRef}>
								<button
									className="toolbar-action"
									onClick={() => setIsStartMenuOpen((prev) => !prev)}
								>
									{renderActionIcon(action)}
									开始
									<span className="dropdown-caret">▾</span>
								</button>
								{isStartMenuOpen && (
									<div className="toolbar-menu">
										<button
											className="toolbar-menu-item"
											onClick={() => {
												setIsStartMenuOpen(false);
												onActionClick?.('新建意图');
											}}
										>
											新建
										</button>
										<button
											className="toolbar-menu-item"
											onClick={() => {
												setIsStartMenuOpen(false);
												onActionClick?.('打开');
											}}
										>
											打开
										</button>
									</div>
								)}
							</div>
						);
					}

					return (
						<button
							key={index}
							className={`${getActionClassName(action)} ${isActionLoading(action) ? 'loading' : ''}`}
							onClick={() => onActionClick?.(action)}
							disabled={isActionLoading(action)}
						>
							{renderActionIcon(action)}
							{isActionLoading(action) && <span className="toolbar-spinner" />}
							{getActionLabel(action)}
						</button>
					);
				})}
			</div>
			<div className="toolbar-right">
				<div className="toolbar-kb-selector" ref={kbMenuRef}>
					<button 
						className="toolbar-kb-btn"
						onClick={() => setIsKbMenuOpen(prev => !prev)}
						title={selectedKb.description}
					>
						<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
							<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
							<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
						</svg>
						<span className="kb-name">{selectedKb.name}</span>
						<span className="dropdown-caret">▾</span>
					</button>
					{isKbMenuOpen && (
						<div className="toolbar-kb-menu">
							<div className="kb-menu-header">选择知识库</div>
							{knowledgeBases.map(kb => (
								<button
									key={kb.id}
									className={`toolbar-kb-item ${kb.id === selectedKnowledgeBase ? 'active' : ''}`}
									onClick={() => {
										onKnowledgeBaseChange?.(kb.id);
										setIsKbMenuOpen(false);
									}}
								>
									<span className="kb-item-name">{kb.name}</span>
									{kb.description && <span className="kb-item-desc">{kb.description}</span>}
									{kb.id === selectedKnowledgeBase && <span className="kb-item-check">✓</span>}
								</button>
							))}
						</div>
					)}
				</div>
			</div>
		</div>
	);
};

export default Toolbar;
