import { Button, Dropdown, DropDownProps, Grid, Space } from 'antd';
import React, { Children, cloneElement, useMemo } from 'react';
import { FixedPositionKey } from './typing';

const { useBreakpoint } = Grid;

// 创建上下文传递控制参数
interface ActionBarContextProps {
	maxVisibleItems?: number;
	isMobile?: boolean;
}

const ActionBarContext = React.createContext<ActionBarContextProps>({});

// 封装智能按钮容器
interface SmartActionBarProps extends ActionBarContextProps {
	children: React.ReactNode;
	moreMenuProps?: DropDownProps;
	fixedPositions?: FixedPositionKey[];
}

export default function SmartActionBar(props: SmartActionBarProps) {
	const {
		children,
		fixedPositions = ['edit', 'view', 'delete'],
		maxVisibleItems = 3,
		moreMenuProps,
	} = props;
	const screens = useBreakpoint();
	const isMobile = !screens.md;
	const contextValue = { maxVisibleItems, isMobile };

	const sortedChildren = useMemo(() => {
		const fixedMap = new Map<FixedPositionKey, React.ReactNode>();
		const dynamicBefore = new Map<FixedPositionKey, React.ReactNode[]>();
		const dynamicAfter = new Map<FixedPositionKey, React.ReactNode[]>();
		const otherChildren: React.ReactNode[] = [];

		Children.forEach(children, (child) => {
			if (!React.isValidElement(child)) return;
			// 权限校验
			const { permissions, currentPermissions } = child.props;
			if (
				permissions &&
				!permissions.some((p: any) => currentPermissions?.includes(p))
			) {
				return;
			}
			// 处理固定位置元素
			const positionKey = child.props.positionKey;
			if (positionKey && fixedPositions.includes(positionKey)) {
				fixedMap.set(positionKey, child);
				return;
			}
			// 处理动态位置元素
			const insertPosition = child.props.insertPosition;
			if (insertPosition) {
				const [position, key] = insertPosition.split(':') as [
					string,
					FixedPositionKey,
				];
				const targetMap = position === 'before' ? dynamicBefore : dynamicAfter;
				if (targetMap.has(key)) {
					targetMap.get(key)!.push(child);
				} else {
					targetMap.set(key, [child]);
				}
			} else {
				otherChildren.push(child);
			}
		});
		// 构建最终排序数组
		const result: React.ReactNode[] = [];
		fixedPositions.forEach((key) => {
			// 添加 before 动态按钮
			if (dynamicBefore.has(key)) {
				result.push(...dynamicBefore.get(key)!);
			}
			// 添加固定按钮
			if (fixedMap.has(key)) {
				result.push(fixedMap.get(key));
			}
			// 添加 after 动态按钮
			if (dynamicAfter.has(key)) {
				result.push(...dynamicAfter.get(key)!);
			}
		});

		// 添加未指定位置的按钮
		result.push(...otherChildren);
		return result;
	}, [children, fixedPositions, maxVisibleItems]);

	// 响应式分组
	const [visibleItems, hiddenItems] = useMemo(() => {
		const maxVisible = isMobile ? 2 : 3;
		return [
			sortedChildren.slice(0, maxVisible),
			sortedChildren.slice(maxVisible),
		];
	}, [sortedChildren, isMobile]);

	return (
		<ActionBarContext.Provider value={contextValue}>
			<Space wrap={false}>
				{/* 常显按钮区域 */}
				{visibleItems.map((child, index) =>
					cloneElement(child as React.ReactElement, {
						key: `visible-${index}`,
					}),
				)}

				{/* 更多菜单 */}
				{hiddenItems.length > 0 && (
					<Dropdown
						menu={{
							items: hiddenItems.map((child, index) => ({
								key: `hidden-${index}`,
								label: cloneElement(child as React.ReactElement, {
									style: { width: '100%' },
								}),
							})),
						}}
						arrow={true}
						{...moreMenuProps}
					>
						<Button
							type={'link'}
							size={'small'}
							onClick={(e) => e.preventDefault()}
						>
							<Space>更多 ▾</Space>
						</Button>
					</Dropdown>
				)}
			</Space>
		</ActionBarContext.Provider>
	);
}
