"use client";

import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { StatsDataItem } from '@/lib/hooks/use-stats-data';

interface StatsSelectProps {
  value: string;
  onValueChange: (value: string) => void;
  placeholder: string;
  inputPlaceholder: string;
  items: StatsDataItem[];
  showNoneOption?: boolean;
  noneOptionLabel?: string;
  className?: string;
  disabled?: boolean;
}

export function StatsSelect({
  value,
  onValueChange,
  placeholder,
  inputPlaceholder,
  items,
  showNoneOption = false,
  noneOptionLabel = "不修改",
  className,
  disabled = false
}: StatsSelectProps) {
  const handleSelectChange = (selectedValue: string) => {
    if (selectedValue === 'none') {
      onValueChange('');
    } else {
      onValueChange(selectedValue);
    }
  };

  // 检查当前值是否在选项列表中
  const isValueInOptions = value && (
    showNoneOption && value === '' || 
    items.some(item => item.value === value)
  );

  // 为Select组件确定显示值
  const selectValue = () => {
    if (!value && showNoneOption) return 'none';
    if (isValueInOptions) return value;
    return undefined; // 如果值不在选项中，不设置Select的值
  };

  return (
    <div className={`space-y-2 ${className || ''}`}>
      <Select 
        value={selectValue()} 
        onValueChange={handleSelectChange}
        disabled={disabled}
      >
        <SelectTrigger className="w-full">
          <SelectValue placeholder={placeholder} />
        </SelectTrigger>
        <SelectContent>
          {showNoneOption && (
            <SelectItem value="none">{noneOptionLabel}</SelectItem>
          )}
          {items.map((item) => (
            <SelectItem key={item.value} value={item.value}>
              {item.label} ({item.count} 个账户)
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Input
        placeholder={inputPlaceholder}
        value={value}
        onChange={(e) => onValueChange(e.target.value)}
        disabled={disabled}
      />
    </div>
  );
}