import { business } from '@/services';
import { FolderOpenOutlined, FolderOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import type { MenuItemProps } from 'antd';
import { Empty, Menu, message } from 'antd';
import React, { useEffect, useState } from 'react';
import useStyle from './style.style';

interface CategoryTreeProps {
	onCategorySelect: (categoryId?: string, categoryName?: string) => void;
	selectedCategoryId?: string;
}

/**
 * 素材分类树组件（使用 Menu 组件）
 * 支持：展开/收起、显示素材数量
 */
const CategoryTree: React.FC<CategoryTreeProps> = ({
	onCategorySelect,
	selectedCategoryId,
}) => {
	const { styles } = useStyle();
	const [treeData, setTreeData] = useState<BusinessAPI.CategoryVO[]>([]);
	const [loading, setLoading] = useState(false);

	// 获取分类树数据
	const fetchCategoryTree = async () => {
		setLoading(true);
		try {
			const { data } = await business.materialCategory.treeMaterialCategory({
				categoryTreeQry: {},
			});
			if (data) {
				setTreeData(data as BusinessAPI.CategoryVO[]);
			}
		} catch (error) {
			console.error('获取素材分类树失败:', error);
			message.error('获取素材分类树失败');
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchCategoryTree();
	}, []);

	// 转换数据为 Menu Item 格式
	const convertToMenuItems = (nodes: BusinessAPI.CategoryVO[]): any[] => {
		return nodes.map((node) => {
			const menuItem: any = {
				key: node.categoryId,
				label: (
					<div className={styles.menuItemLabel}>
						<span className={styles.categoryName}>{node.name}</span>
						<span className={styles.materialCount}>
							{/* @ts-ignore */}({node.materialCount || 0})
						</span>
					</div>
				),
				icon:
					node.children && node.children.length > 0 ? (
						<FolderOpenOutlined />
					) : (
						<FolderOutlined />
					),
			};

			// 递归处理子节点
			if (node.children && node.children.length > 0) {
				menuItem.children = convertToMenuItems(node.children);
			}

			return menuItem;
		});
	};

	// 处理菜单选择
	const handleMenuSelect: MenuItemProps['onClick'] = ({ key }) => {
		const categoryId = key as string;
		// 从树数据中查找分类名称
		const findCategoryName = (
			nodes: BusinessAPI.CategoryVO[],
			targetId: string,
		): string | undefined => {
			for (const node of nodes) {
				if (node.categoryId === targetId) {
					return node.name;
				}
				if (node.children) {
					const found = findCategoryName(node.children, targetId);
					if (found) return found;
				}
			}
			return undefined;
		};

		const categoryName = findCategoryName(treeData, categoryId);
		onCategorySelect(categoryId, categoryName);
	};

	const menuItems = convertToMenuItems(treeData);

	return (
		<ProCard
			title={
				<div className={styles.cardHeader}>
					<span>素材分类</span>
				</div>
			}
			size="small"
			className={styles.categoryCard}
			loading={loading}
		>
			{menuItems.length > 0 ? (
				<Menu
					mode="inline"
					selectedKeys={selectedCategoryId ? [selectedCategoryId] : []}
					onClick={handleMenuSelect}
					items={menuItems}
					className={styles.categoryMenu}
				/>
			) : (
				<Empty description="暂无分类" image={Empty.PRESENTED_IMAGE_SIMPLE} />
			)}
		</ProCard>
	);
};

export default CategoryTree;
