/**
 * 优化的搜索输入组件
 * 
 * 功能：
 * 1. 防抖搜索（默认 300ms）
 * 2. 搜索历史
 * 3. 清空按钮
 * 4. 搜索建议（可选）
 * 5. 快捷键支持（Ctrl/Cmd + K）
 */

'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, X, Clock, TrendingUp } from 'lucide-react';
import { useDebounce } from '@/hooks/useDebounce';

export interface SearchInputProps {
  /** 搜索值 */
  value: string;
  /** 搜索值变化回调 */
  onChange: (value: string) => void;
  /** 占位符 */
  placeholder?: string;
  /** 防抖延迟（毫秒） */
  debounceDelay?: number;
  /** 是否启用搜索历史 */
  enableHistory?: boolean;
  /** 搜索历史存储键名 */
  historyKey?: string;
  /** 最大历史记录数 */
  maxHistory?: number;
  /** 搜索建议列表 */
  suggestions?: string[];
  /** 是否显示热门搜索 */
  showTrending?: boolean;
  /** 热门搜索列表 */
  trendingSearches?: string[];
  /** 自定义样式类名 */
  className?: string;
  /** 是否自动聚焦 */
  autoFocus?: boolean;
}

export function SearchInput({
  value,
  onChange,
  placeholder = '搜索...',
  debounceDelay = 300,
  enableHistory = true,
  historyKey = 'search_history',
  maxHistory = 10,
  suggestions = [],
  showTrending = false,
  trendingSearches = [],
  className = '',
  autoFocus = false,
}: SearchInputProps) {
  const [inputValue, setInputValue] = useState(value);
  const [isFocused, setIsFocused] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 防抖后的值
  const debouncedValue = useDebounce(inputValue, debounceDelay);

  // 加载搜索历史
  useEffect(() => {
    if (enableHistory && typeof window !== 'undefined') {
      const history = localStorage.getItem(historyKey);
      if (history) {
        try {
          setSearchHistory(JSON.parse(history));
        } catch (e) {
          console.error('Failed to parse search history:', e);
        }
      }
    }
  }, [enableHistory, historyKey]);

  // 防抖后触发搜索
  useEffect(() => {
    if (debouncedValue !== value) {
      onChange(debouncedValue);
      
      // 保存到搜索历史
      if (debouncedValue && enableHistory) {
        saveToHistory(debouncedValue);
      }
    }
  }, [debouncedValue]);

  // 保存搜索历史
  const saveToHistory = (query: string) => {
    if (!query.trim() || typeof window === 'undefined') return;

    const newHistory = [
      query,
      ...searchHistory.filter(h => h !== query),
    ].slice(0, maxHistory);

    setSearchHistory(newHistory);
    localStorage.setItem(historyKey, JSON.stringify(newHistory));
  };

  // 清除搜索历史
  const clearHistory = () => {
    setSearchHistory([]);
    if (typeof window !== 'undefined') {
      localStorage.removeItem(historyKey);
    }
  };

  // 从历史或建议中选择
  const handleSelect = (query: string) => {
    setInputValue(query);
    onChange(query);
    setShowDropdown(false);
    inputRef.current?.blur();
  };

  // 清空搜索
  const handleClear = () => {
    setInputValue('');
    onChange('');
    inputRef.current?.focus();
  };

  // 点击外部关闭下拉
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node) &&
        inputRef.current &&
        !inputRef.current.contains(event.target as Node)
      ) {
        setShowDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 快捷键支持（Ctrl/Cmd + K）
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
        event.preventDefault();
        inputRef.current?.focus();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  // 判断是否显示下拉菜单
  const shouldShowDropdown = 
    isFocused &&
    showDropdown &&
    (
      (enableHistory && searchHistory.length > 0) ||
      (showTrending && trendingSearches.length > 0) ||
      suggestions.length > 0
    );

  // 过滤建议（根据当前输入）
  const filteredSuggestions = suggestions.filter(s =>
    s.toLowerCase().includes(inputValue.toLowerCase())
  );

  return (
    <div className={`relative ${className}`}>
      {/* 搜索输入框 */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input
          ref={inputRef}
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onFocus={() => {
            setIsFocused(true);
            setShowDropdown(true);
          }}
          onBlur={() => setIsFocused(false)}
          placeholder={placeholder}
          autoFocus={autoFocus}
          className="
            w-full
            pl-10 pr-10 py-2
            border border-gray-300 rounded-lg
            text-sm
            outline-none
            focus:ring-2 focus:ring-blue-400 focus:border-blue-400
            transition-all
          "
        />
        {inputValue && (
          <button
            onClick={handleClear}
            className="
              absolute right-3 top-1/2 -translate-y-1/2
              p-1 rounded-full
              hover:bg-gray-100
              transition-colors
            "
          >
            <X className="w-4 h-4 text-gray-400" />
          </button>
        )}
      </div>

      {/* 下拉菜单：历史记录 + 建议 + 热门搜索 */}
      {shouldShowDropdown && (
        <div
          ref={dropdownRef}
          className="
            absolute top-full left-0 right-0 mt-1
            bg-white rounded-lg shadow-lg border border-gray-200
            max-h-80 overflow-y-auto
            z-50
          "
        >
          {/* 搜索历史 */}
          {enableHistory && searchHistory.length > 0 && (
            <div className="py-2">
              <div className="flex items-center justify-between px-4 py-2">
                <div className="flex items-center gap-2 text-xs font-medium text-gray-500">
                  <Clock className="w-3 h-3" />
                  <span>搜索历史</span>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    clearHistory();
                  }}
                  className="text-xs text-gray-400 hover:text-gray-600"
                >
                  清除
                </button>
              </div>
              {searchHistory.map((item, index) => (
                <button
                  key={`history-${index}`}
                  onClick={() => handleSelect(item)}
                  className="
                    w-full px-4 py-2 text-left text-sm
                    hover:bg-gray-50
                    flex items-center gap-2
                  "
                >
                  <Clock className="w-4 h-4 text-gray-400" />
                  <span className="flex-1 truncate">{item}</span>
                </button>
              ))}
            </div>
          )}

          {/* 搜索建议 */}
          {filteredSuggestions.length > 0 && (
            <div className="py-2 border-t border-gray-100">
              <div className="px-4 py-2 text-xs font-medium text-gray-500">
                搜索建议
              </div>
              {filteredSuggestions.map((item, index) => (
                <button
                  key={`suggestion-${index}`}
                  onClick={() => handleSelect(item)}
                  className="
                    w-full px-4 py-2 text-left text-sm
                    hover:bg-gray-50
                    flex items-center gap-2
                  "
                >
                  <Search className="w-4 h-4 text-gray-400" />
                  <span className="flex-1 truncate">{item}</span>
                </button>
              ))}
            </div>
          )}

          {/* 热门搜索 */}
          {showTrending && trendingSearches.length > 0 && !inputValue && (
            <div className="py-2 border-t border-gray-100">
              <div className="flex items-center gap-2 px-4 py-2 text-xs font-medium text-gray-500">
                <TrendingUp className="w-3 h-3" />
                <span>热门搜索</span>
              </div>
              {trendingSearches.map((item, index) => (
                <button
                  key={`trending-${index}`}
                  onClick={() => handleSelect(item)}
                  className="
                    w-full px-4 py-2 text-left text-sm
                    hover:bg-gray-50
                    flex items-center gap-2
                  "
                >
                  <TrendingUp className="w-4 h-4 text-orange-400" />
                  <span className="flex-1 truncate">{item}</span>
                  <span className="text-xs text-gray-400">#{index + 1}</span>
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * 搜索优化 Hook
 * 
 * 使用示例：
 * ```tsx
 * const { searchQuery, setSearchQuery, debouncedQuery, isSearching } = useOptimizedSearch();
 * ```
 */
export function useOptimizedSearch(debounceDelay = 300) {
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  const debouncedQuery = useDebounce(searchQuery, debounceDelay);

  useEffect(() => {
    if (searchQuery !== debouncedQuery) {
      setIsSearching(true);
    } else {
      setIsSearching(false);
    }
  }, [searchQuery, debouncedQuery]);

  const clearSearch = useCallback(() => {
    setSearchQuery('');
  }, []);

  return {
    searchQuery,
    setSearchQuery,
    debouncedQuery,
    isSearching,
    clearSearch,
  };
}

