'use client';

import * as React from 'react';
import { useState, useRef } from 'react';
import { Button } from '@nice/ui/components/button';
import { Popover, PopoverContent, PopoverTrigger } from '@nice/ui/components/popover';
import {
	Command,
	CommandEmpty,
	CommandGroup,
	CommandItem,
	CommandList,
} from '@nice/ui/components/command';
import { IconChevronDown, IconCheck, IconStarFilled, IconX } from '@tabler/icons-react';
import { cn } from '@nice/ui/lib/utils';
import { Badge } from '@nice/ui/components/badge';
import { DutyLevel } from '@fenghuo/common';

// 职务等级选项定义
const DUTY_LEVEL_OPTIONS = [
	{ value: 3, label: DutyLevel.HIGH },
	{ value: 2, label: DutyLevel.MIDDLE },
	{ value: 1, label: DutyLevel.PRIMARY },
];

// 职务等级选择器属性
interface DutyLevelSelectorProps {
	value?: number | number[]; // 支持单选和多选
	onValueChange?: (value: number | number[]) => void;
	placeholder?: string;
	className?: string;
	disabled?: boolean;
	allowClear?: boolean;
	multiple?: boolean; // 是否支持多选
	modal?: boolean; // 是否为模态模式，用于在 Dialog 中解决滚轮问题
}

// 职务等级星星显示组件
function DutyLevelStars({ level }: { level: number }) {
	const stars = Array.from({ length: level }, (_, index) => (
		<IconStarFilled key={index} className="size-3 text-yellow-500" />
	));
	return <div className="flex items-center gap-0.5">{stars}</div>;
}

// 职务等级选项组件
interface DutyLevelItemProps {
	option: { value: number; label: string };
	isSelected: boolean;
	onSelect: () => void;
}

function DutyLevelItem({ option, isSelected, onSelect }: DutyLevelItemProps) {
	return (
		<CommandItem
			value={`${option.value}-${option.label}`}
			onSelect={onSelect}
			className={cn(
				'flex items-center justify-between cursor-pointer p-3',
				'hover:bg-primary/10 hover:text-primary hover:font-medium',
				isSelected && 'bg-accent text-primary font-medium',
			)}
		>
			<div className="flex items-center gap-3 flex-1 min-w-0">
				{/* 星星图标 */}
				<DutyLevelStars level={option.value} />

				{/* 等级信息 */}
				<div className="flex-1 min-w-0">
					<span className="font-medium">{option.label}</span>
				</div>
			</div>

			{/* 选中状态指示 */}
			{isSelected && <IconCheck className="h-4 w-4 text-primary shrink-0" />}
		</CommandItem>
	);
}

// 主组件
export function DutyLevelSelect({
	value,
	onValueChange,
	placeholder = '选择职务等级',
	className,
	disabled = false,
	allowClear = true,
	multiple = false,
	modal = false,
}: DutyLevelSelectorProps) {
	const [open, setOpen] = useState(false);
	const containerRef = useRef<HTMLDivElement>(null);

	// 获取选中的职务等级
	const selectedLevels = React.useMemo(() => {
		if (!value) return [];

		const selectedValues = Array.isArray(value) ? value : [value];
		return DUTY_LEVEL_OPTIONS.filter((option) => selectedValues.includes(option.value));
	}, [value]);

	// 处理选择逻辑
	const handleSelect = (levelValue: number) => {
		if (!onValueChange) return;

		if (multiple) {
			const currentValues = Array.isArray(value) ? value : value ? [value] : [];

			if (currentValues.includes(levelValue)) {
				// 取消选择
				const newValues = currentValues.filter((val) => val !== levelValue);
				onValueChange(newValues);
			} else {
				// 添加选择
				onValueChange([...currentValues, levelValue]);
			}
		} else {
			// 单选模式
			onValueChange(levelValue);
			setOpen(false);
		}
	};

	// 清除选择
	const handleClear = (e: React.MouseEvent) => {
		e.preventDefault();
		e.stopPropagation();
		onValueChange?.(multiple ? [] : 0);
	};

	// 处理单个职务等级移除（仅多选模式）
	const handleRemoveLevel = (levelValue: number, e: React.MouseEvent) => {
		e.preventDefault();
		e.stopPropagation();
		if (multiple) {
			const currentValues = Array.isArray(value) ? value : value ? [value] : [];
			const newValues = currentValues.filter((val) => val !== levelValue);
			onValueChange?.(newValues);
		}
	};

	// 渲染触发器内容
	const renderTriggerContent = () => {
		if (selectedLevels.length === 0) {
			return placeholder;
		}

		if (multiple) {
			if (selectedLevels.length === 1) {
				return (
					<div className="flex items-center gap-2">
						<DutyLevelStars level={selectedLevels[0]!.value} />
						<span>{selectedLevels[0]!.label}</span>
					</div>
				);
			} else {
				return (
					<div className="flex flex-wrap gap-1 justify-start">
						{selectedLevels.slice(0, 1).map((level) => (
							<Badge key={level.value} variant="secondary" className="text-xs px-1.5 py-0.5 h-5 max-w-[140px]">
								<div className="flex items-center gap-1">
									<DutyLevelStars level={level.value} />
									<span className="truncate">{level.label}</span>
								</div>
								<span
									onClick={(e) => handleRemoveLevel(level.value, e)}
									className="ml-1 hover:bg-muted-foreground/20 rounded-sm p-0.5 cursor-pointer inline-flex items-center justify-center"
									role="button"
									tabIndex={0}
									aria-label={`移除职务等级 ${level.label}`}
									onKeyDown={(e) => {
										if (e.key === 'Enter' || e.key === ' ') {
											e.preventDefault();
											handleRemoveLevel(level.value, e as any);
										}
									}}
								>
									<IconX className="h-2.5 w-2.5" />
								</span>
							</Badge>
						))}
						{selectedLevels.length > 1 && (
							<Badge variant="secondary" className="text-xs px-1.5 py-0.5 h-5">
								+{selectedLevels.length - 1}
							</Badge>
						)}
					</div>
				);
			}
		}

		return (
			<div className="flex items-center gap-2">
				<DutyLevelStars level={selectedLevels[0]!.value} />
				<span>{selectedLevels[0]!.label}</span>
			</div>
		);
	};

	// 检查是否选中
	const isSelected = (levelValue: number) => {
		if (!value) return false;
		return Array.isArray(value) ? value.includes(levelValue) : value === levelValue;
	};

	return (
		<div ref={containerRef}>
			<Popover open={open} onOpenChange={setOpen} modal={modal}>
				<PopoverTrigger asChild>
					<Button
						variant="outline"
						role="combobox"
						aria-expanded={open}
						className={cn(
							'w-full justify-start text-left font-normal',
							!selectedLevels.length && 'text-muted-foreground',
							className,
						)}
						disabled={disabled}
					>
						<div className="flex items-center gap-2 flex-1 min-w-0">
							<IconStarFilled className="h-4 w-4 text-muted-foreground shrink-0" />
							<div className="flex-1 min-w-0 text-left">{renderTriggerContent()}</div>
						</div>

						<div className="flex items-center gap-1 shrink-0 ml-auto">
							{allowClear && selectedLevels.length > 0 && (
								<span
									onClick={handleClear}
									className="flex items-center justify-center w-4 h-4 rounded-sm hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
									role="button"
									tabIndex={0}
									aria-label="清除选择"
									onKeyDown={(e) => {
										if (e.key === 'Enter' || e.key === ' ') {
											e.preventDefault();
											handleClear(e as any);
										}
									}}
								>
									<IconX className="h-3 w-3" />
								</span>
							)}
							<IconChevronDown className="h-4 w-4 shrink-0 opacity-50" />
						</div>
					</Button>
				</PopoverTrigger>

				<PopoverContent className="w-full p-0" style={{ width: 'var(--radix-popover-trigger-width)' }} align="start">
					<Command shouldFilter={false}>
						<CommandList className="max-h-[250px] overflow-y-auto">
							{DUTY_LEVEL_OPTIONS.length === 0 ? (
								<CommandEmpty>未找到职务等级</CommandEmpty>
							) : (
								<CommandGroup>
									{/* 多选模式下显示已选择数量 */}
									{multiple && selectedLevels.length > 0 && (
										<div className="px-2 py-1.5 text-xs text-muted-foreground border-b">
											已选择 {selectedLevels.length} 个职务等级
										</div>
									)}
									{DUTY_LEVEL_OPTIONS.map((option) => (
										<DutyLevelItem
											key={option.value}
											option={option}
											isSelected={isSelected(option.value)}
											onSelect={() => handleSelect(option.value)}
										/>
									))}
								</CommandGroup>
							)}
						</CommandList>
					</Command>
				</PopoverContent>
			</Popover>
		</div>
	);
}

// 导出便捷的单选和多选组件
export function SingleDutyLevelSelector(
	props: Omit<DutyLevelSelectorProps, 'multiple' | 'onValueChange'> & {
		onValueChange?: (value: number) => void;
	},
) {
	const handleValueChange = (value: number | number[]) => {
		if (props.onValueChange && typeof value === 'number') {
			props.onValueChange(value);
		}
	};

	return <DutyLevelSelect {...props} multiple={false} onValueChange={handleValueChange} />;
}

export function MultipleDutyLevelSelector(
	props: Omit<DutyLevelSelectorProps, 'multiple' | 'onValueChange'> & {
		onValueChange?: (value: number[]) => void;
	},
) {
	const handleValueChange = (value: number | number[]) => {
		if (props.onValueChange && Array.isArray(value)) {
			props.onValueChange(value);
		}
	};

	return <DutyLevelSelect {...props} multiple={true} onValueChange={handleValueChange} />;
}