import React, { useCallback, useRef, useEffect } from 'react';
import {
  Search,
  Sparkles,
  Loader2,
  Filter,
  ChevronDown
} from 'lucide-react';
import { 
  SimilaritySearchPanelProps, 
  SimilaritySearchRequest 
} from '../../types/similaritySearch';
import SimilaritySearchService from '../../services/similaritySearchService';

/**
 * 相似度检索搜索面板组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const SimilaritySearchPanel: React.FC<SimilaritySearchPanelProps> = ({
  query,
  selectedThreshold,
  suggestions,
  showSuggestions,
  isSearching,
  onQueryChange,
  onSearch,
  onSuggestionSelect,
  onSuggestionsToggle,
  onOutfitRecommendation,
  showAdvancedFilters,
  onToggleAdvancedFilters,
}) => {
  const inputRef = useRef<HTMLInputElement>(null);

  // 处理搜索执行
  const handleSearch = useCallback(() => {
    if (!SimilaritySearchService.validateQuery(query)) {
      return;
    }

    const request: SimilaritySearchRequest = {
      query: query.trim(),
      relevance_threshold: selectedThreshold,
    };

    onSearch(request);
  }, [query, selectedThreshold, onSearch]);

  // 处理穿搭方案生成
  const handleOutfitRecommendation = useCallback((e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (onOutfitRecommendation) {
      onOutfitRecommendation();
    }
  }, [onOutfitRecommendation]);

  // 处理回车键搜索
  const handleKeyPress = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSearch();
    }
  }, [handleSearch]);

  // 处理建议选择
  const handleSuggestionClick = useCallback((suggestion: string) => {
    onSuggestionSelect(suggestion);
  }, [onSuggestionSelect]);

  // 处理输入框焦点
  const handleInputFocus = useCallback(() => {
    if (suggestions.length > 0) {
      onSuggestionsToggle(true);
    }
  }, [suggestions.length, onSuggestionsToggle]);

  // 处理输入框失焦
  const handleInputBlur = useCallback(() => {
    // 延迟隐藏建议，允许点击建议
    setTimeout(() => {
      onSuggestionsToggle(false);
    }, 200);
  }, [onSuggestionsToggle]);

  // 自动聚焦输入框
  useEffect(() => {
    if (inputRef.current && !query) {
      inputRef.current.focus();
    }
  }, [query]);

  return (
    <div className="space-y-6">
      {/* 搜索输入区域 */}
      <div className="card p-6 animate-fade-in">
        <div className="flex items-center gap-3 mb-4">
          <div className="icon-container primary w-8 h-8">
            <Search className="w-4 h-4" />
          </div>
          <div>
            <h3 className="text-heading-4 text-high-emphasis">智能搜索</h3>
            <p className="text-xs text-medium-emphasis">输入关键词进行相似度检索</p>
          </div>
        </div>

        <div className="relative">
          <div className="flex flex-col gap-3">
            <div className="flex-1 relative group">
              <input
                ref={inputRef}
                type="text"
                value={query}
                onChange={(e) => onQueryChange(e.target.value)}
                onKeyDown={handleKeyPress}
                onFocus={handleInputFocus}
                onBlur={handleInputBlur}
                placeholder="输入搜索关键词，如：休闲搭配、牛仔裤、正式风格..."
                className="form-input pr-12 group-hover:border-primary-300 focus:border-primary-500 transition-colors duration-200"
                disabled={isSearching}
              />
              <button
                type="button"
                onClick={handleOutfitRecommendation}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-primary-500 transition-colors duration-200 p-1 rounded-full hover:bg-primary-50"
                title="生成AI穿搭方案推荐"
                disabled={isSearching}
              >
                <Sparkles className="w-5 h-5" />
              </button>
            </div>
            
            <button
              onClick={handleSearch}
              disabled={isSearching || !SimilaritySearchService.validateQuery(query)}
              className="btn btn-primary px-6 min-w-[100px] disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSearching ? (
                <div className="flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span>搜索中</span>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <Search className="w-4 h-4" />
                  <span>搜索</span>
                </div>
              )}
            </button>
          </div>

          {/* 搜索建议下拉 */}
          {showSuggestions && suggestions.length > 0 && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg z-50 animate-slide-in-up">
              <div className="p-2">
                <div className="text-xs text-gray-500 px-3 py-2 border-b border-gray-100">
                  搜索建议
                </div>
                <div className="max-h-60 overflow-y-auto">
                  {suggestions.map((suggestion, index) => (
                    <button
                      key={index}
                      onClick={() => handleSuggestionClick(suggestion)}
                      className="w-full text-left px-3 py-2 hover:bg-gray-50 rounded-lg transition-colors duration-200 flex items-center gap-2"
                    >
                      <Search className="w-4 h-4 text-gray-400" />
                      <span className="text-sm text-gray-700">{suggestion}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>



      {/* 搜索提示 */}
      <div className="card p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 animate-fade-in">
        <div className="flex items-start gap-3">
          <div className="icon-container blue w-6 h-6 mt-0.5 shadow-sm">
            <Sparkles className="w-3 h-3" />
          </div>
          <div className="flex-1">
            <h4 className="text-sm font-semibold text-blue-900 mb-2">💡 搜索提示</h4>
            <ul className="text-xs text-blue-700 space-y-1.5">
              <li className="flex items-center gap-2">
                <div className="w-1 h-1 bg-blue-400 rounded-full"></div>
                使用具体的关键词获得更精准的结果
              </li>
              <li className="flex items-center gap-2">
                <div className="w-1 h-1 bg-blue-400 rounded-full"></div>
                可以组合多个关键词，如"休闲 牛仔裤"
              </li>
              <li className="flex items-center gap-2">
                <div className="w-1 h-1 bg-blue-400 rounded-full"></div>
                使用顶部的相关性阈值来控制结果数量
              </li>
            </ul>
          </div>
        </div>
      </div>

      {/* 高级过滤器切换按钮 */}
      {onToggleAdvancedFilters && (
        <div className="card p-3 bg-gradient-to-r from-purple-50 to-pink-50 border border-purple-200 animate-fade-in">
          <button
            onClick={onToggleAdvancedFilters}
            className="w-full flex items-center justify-between p-2 rounded-lg hover:bg-white hover:bg-opacity-50 transition-all duration-200 group"
          >
            <div className="flex items-center gap-3">
              <div className="icon-container purple w-6 h-6 shadow-sm">
                <Filter className="w-3 h-3" />
              </div>
              <div className="text-left">
                <h4 className="text-sm font-semibold text-purple-900">高级过滤器</h4>
                <p className="text-xs text-purple-700">
                  {showAdvancedFilters ? '点击收起高级过滤选项' : '精确控制搜索条件'}
                </p>
              </div>
            </div>
            <ChevronDown
              className={`w-4 h-4 text-purple-600 transition-transform duration-200 ${
                showAdvancedFilters ? 'rotate-180' : ''
              }`}
            />
          </button>
        </div>
      )}
    </div>
  );
};

export default SimilaritySearchPanel;
