import React, { useState, useCallback } from 'react';
import { MapPin, Plus, X, Search, Tag } from 'lucide-react';

/**
 * 环境标签选择器组件
 * 遵循 promptx/frontend-developer 标准的UI/UX优化
 */

interface EnvironmentTagSelectorProps {
  selectedEnvironments: string[];
  availableEnvironments?: string[]; // 现在可选，因为我们使用内置的环境分组
  onEnvironmentsChange: (environments: string[]) => void;
  maxSelections?: number;
  allowCustom?: boolean;
  className?: string;
}

export const EnvironmentTagSelector: React.FC<EnvironmentTagSelectorProps> = ({
  selectedEnvironments,
  onEnvironmentsChange,
  maxSelections = 3,
  allowCustom = true,
  className = '',
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [showCustomInput, setShowCustomInput] = useState(false);
  const [customEnvironment, setCustomEnvironment] = useState('');

  // 环境标签分组
  const environmentGroups: Record<string, string[]> = {
    '室内环境': ['Indoor', 'Office', 'Home', 'Restaurant', 'Shopping mall'],
    '室外环境': ['Outdoor', 'City street', 'Park', 'Beach', 'Mountain'],
    '建筑环境': ['Building facade', 'Modern architecture', 'Historic building'],
    '自然环境': ['Natural setting', 'Garden', 'Forest', 'Countryside'],
  };

  // 过滤可用环境
  const getFilteredEnvironments = useCallback(() => {
    if (!searchQuery) {
      return environmentGroups;
    }

    const filtered: Record<string, string[]> = {};
    Object.entries(environmentGroups).forEach(([group, environments]) => {
      const matchedEnvironments = environments.filter(env =>
        env.toLowerCase().includes(searchQuery.toLowerCase()) &&
        !selectedEnvironments.includes(env)
      );
      if (matchedEnvironments.length > 0) {
        filtered[group] = matchedEnvironments;
      }
    });

    return filtered;
  }, [searchQuery, selectedEnvironments]);

  const filteredGroups = getFilteredEnvironments();

  // 处理环境选择
  const handleEnvironmentSelect = useCallback((environment: string) => {
    if (selectedEnvironments.includes(environment)) {
      onEnvironmentsChange(selectedEnvironments.filter(e => e !== environment));
    } else if (selectedEnvironments.length < maxSelections) {
      onEnvironmentsChange([...selectedEnvironments, environment]);
    }
  }, [selectedEnvironments, onEnvironmentsChange, maxSelections]);

  // 处理自定义环境添加
  const handleCustomEnvironmentAdd = useCallback(() => {
    const trimmedEnvironment = customEnvironment.trim();
    if (trimmedEnvironment && 
        !selectedEnvironments.includes(trimmedEnvironment) && 
        selectedEnvironments.length < maxSelections) {
      onEnvironmentsChange([...selectedEnvironments, trimmedEnvironment]);
      setCustomEnvironment('');
      setShowCustomInput(false);
    }
  }, [customEnvironment, selectedEnvironments, onEnvironmentsChange, maxSelections]);

  // 处理移除选中环境
  const handleRemoveEnvironment = useCallback((environment: string) => {
    onEnvironmentsChange(selectedEnvironments.filter(e => e !== environment));
  }, [selectedEnvironments, onEnvironmentsChange]);

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 已选择的环境标签 */}
      {selectedEnvironments.length > 0 && (
        <div className="space-y-2">
          <h4 className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <Tag className="w-4 h-4" />
            已选择环境
          </h4>
          <div className="flex flex-wrap gap-2">
            {selectedEnvironments.map((environment) => (
              <div
                key={environment}
                className="inline-flex items-center gap-2 px-3 py-1.5 bg-green-100 text-green-700 rounded-full text-sm font-medium animate-fade-in"
              >
                <MapPin className="w-3 h-3" />
                <span>{environment}</span>
                <button
                  onClick={() => handleRemoveEnvironment(environment)}
                  className="hover:bg-green-200 rounded-full p-0.5 transition-colors duration-150"
                  aria-label={`移除 ${environment}`}
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            ))}
          </div>
          
          {selectedEnvironments.length >= maxSelections && (
            <p className="text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded">
              最多只能选择 {maxSelections} 个环境标签
            </p>
          )}
        </div>
      )}

      {/* 搜索框 */}
      <div className="space-y-2">
        <h4 className="text-sm font-medium text-gray-700">选择环境标签</h4>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="搜索环境标签..."
            className="form-input pl-10 pr-4"
          />
        </div>
      </div>

      {/* 环境标签分组列表 */}
      <div className="space-y-3 max-h-64 overflow-y-auto">
        {Object.entries(filteredGroups).map(([groupName, environments]) => (
          <div key={groupName} className="space-y-2">
            <h5 className="text-xs font-medium text-gray-500 uppercase tracking-wide">
              {groupName}
            </h5>
            <div className="grid grid-cols-1 gap-1">
              {environments.map((environment) => (
                <button
                  key={environment}
                  onClick={() => handleEnvironmentSelect(environment)}
                  disabled={selectedEnvironments.length >= maxSelections && !selectedEnvironments.includes(environment)}
                  className={`flex items-center justify-between px-3 py-2 text-left rounded-lg transition-all duration-150 ${
                    selectedEnvironments.includes(environment)
                      ? 'bg-green-100 text-green-700 border border-green-300'
                      : selectedEnvironments.length >= maxSelections
                      ? 'bg-gray-50 text-gray-400 cursor-not-allowed'
                      : 'bg-white hover:bg-gray-50 border border-gray-200 hover:border-green-300 hover-lift'
                  }`}
                >
                  <div className="flex items-center gap-2">
                    <MapPin className="w-4 h-4 text-gray-400" />
                    <span className="text-sm">{environment}</span>
                  </div>
                  {selectedEnvironments.includes(environment) ? (
                    <X className="w-4 h-4 text-green-600" />
                  ) : (
                    <Plus className="w-4 h-4 text-gray-400" />
                  )}
                </button>
              ))}
            </div>
          </div>
        ))}
        
        {Object.keys(filteredGroups).length === 0 && searchQuery && (
          <div className="text-center py-4 text-gray-500">
            <p className="text-sm">未找到匹配的环境标签</p>
            {allowCustom && selectedEnvironments.length < maxSelections && (
              <button
                onClick={() => {
                  setCustomEnvironment(searchQuery);
                  setShowCustomInput(true);
                }}
                className="text-green-600 hover:text-green-700 text-sm mt-1"
              >
                添加 "{searchQuery}" 为自定义环境
              </button>
            )}
          </div>
        )}
      </div>

      {/* 自定义环境输入 */}
      {allowCustom && selectedEnvironments.length < maxSelections && (
        <div className="space-y-2">
          {!showCustomInput ? (
            <button
              onClick={() => setShowCustomInput(true)}
              className="w-full flex items-center justify-center gap-2 px-3 py-2 border-2 border-dashed border-gray-300 rounded-lg text-gray-600 hover:border-green-400 hover:text-green-600 transition-all duration-200"
            >
              <Plus className="w-4 h-4" />
              <span className="text-sm">添加自定义环境</span>
            </button>
          ) : (
            <div className="flex gap-2">
              <input
                type="text"
                value={customEnvironment}
                onChange={(e) => setCustomEnvironment(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleCustomEnvironmentAdd();
                  } else if (e.key === 'Escape') {
                    setShowCustomInput(false);
                    setCustomEnvironment('');
                  }
                }}
                placeholder="输入自定义环境名称"
                className="flex-1 form-input"
                autoFocus
              />
              <button
                onClick={handleCustomEnvironmentAdd}
                disabled={!customEnvironment.trim()}
                className="btn btn-primary btn-sm"
              >
                <Plus className="w-4 h-4" />
              </button>
              <button
                onClick={() => {
                  setShowCustomInput(false);
                  setCustomEnvironment('');
                }}
                className="btn btn-ghost btn-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      )}

      {/* 使用提示 */}
      <div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
        <p>🌍 提示：环境标签帮助匹配特定场景下的搭配风格</p>
      </div>
    </div>
  );
};
