import React, { useEffect, useCallback } from 'react';
import { 
  Search, 
  Sparkles, 
  RotateCcw, 
  TrendingUp,
  Zap,
  ArrowLeft
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { 
  useSimilaritySearchStore, 
  useSimilaritySearchSelectors, 
  useSimilaritySearchActions 
} from '../../store/similaritySearchStore';
import { SimilaritySearchPanel } from '../../components/similarity/SimilaritySearchPanel';
import { SimilaritySearchResults } from '../../components/similarity/SimilaritySearchResults';
import { SimilaritySearchRequest } from '../../types/similaritySearch';

/**
 * 相似度检索工具页面
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const SimilaritySearchTool: React.FC = () => {
  const navigate = useNavigate();

  // 状态管理
  const {
    query,
    selectedThreshold,
    setQuery,
    setThreshold,
    executeSearch,
    loadConfig,
    clearError,
    setShowSuggestions,
  } = useSimilaritySearchStore();

  // 选择器
  const { useSearchState, useConfigState, useSuggestionsState } = useSimilaritySearchSelectors();
  const { quickSearch, resetAll, selectSuggestionAndSearch } = useSimilaritySearchActions();

  // 获取状态
  const searchState = useSearchState();
  const configState = useConfigState();
  const suggestionsState = useSuggestionsState();

  // 页面初始化
  useEffect(() => {
    loadConfig();
    clearError();
  }, [loadConfig, clearError]);

  // 处理搜索
  const handleSearch = useCallback((request: SimilaritySearchRequest) => {
    executeSearch(request);
  }, [executeSearch]);

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

  // 处理快速搜索标签点击
  const handleQuickTagClick = useCallback((tag: string) => {
    quickSearch(tag);
  }, [quickSearch]);

  // 处理重置
  const handleReset = useCallback(() => {
    resetAll();
  }, [resetAll]);

  // 返回工具列表
  const handleBackToTools = useCallback(() => {
    navigate('/tools');
  }, [navigate]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50">
      {/* 页面头部 */}
      <div className="bg-white border-b border-gray-100 shadow-sm">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <button
                onClick={handleBackToTools}
                className="flex items-center gap-2 px-3 py-2 text-gray-600 hover:text-primary-600 hover:bg-gray-50 rounded-lg transition-all duration-200"
              >
                <ArrowLeft className="w-4 h-4" />
                <span className="text-sm font-medium">返回工具</span>
              </button>
              
              <div className="h-6 w-px bg-gray-200"></div>
              
              <div className="flex items-center gap-3">
                <div className="icon-container primary w-10 h-10">
                  <Search className="w-5 h-5" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-high-emphasis">相似度检索工具</h1>
                  <p className="text-sm text-medium-emphasis">基于AI的智能相似度搜索</p>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={handleReset}
                className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all duration-200"
              >
                <RotateCcw className="w-4 h-4" />
                <span className="text-sm font-medium">重置</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-8">
        {/* 快速开始提示 */}
        {!searchState.results.length && !searchState.isSearching && (
          <div className="mb-8 animate-fade-in">
            <div className="card p-6 bg-gradient-to-r from-primary-50 via-blue-50 to-indigo-50 border border-primary-200 shadow-sm">
              <div className="flex items-start gap-4">
                <div className="icon-container primary w-12 h-12 shadow-md">
                  <Sparkles className="w-6 h-6" />
                </div>
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-primary-900 mb-2">🚀 开始您的相似度检索</h3>
                  <p className="text-primary-700 mb-4 leading-relaxed">
                    输入关键词或选择快速标签，AI将为您找到最相似的内容
                  </p>

                  {/* 快速标签 */}
                  {configState.config?.quick_search_tags && (
                    <div className="flex flex-wrap gap-2">
                      {configState.config.quick_search_tags.map((tag) => (
                        <button
                          key={tag}
                          onClick={() => handleQuickTagClick(tag)}
                          className="px-3 py-1.5 bg-white hover:bg-primary-100 text-primary-700 text-sm rounded-full border border-primary-200 transition-all duration-200 flex items-center gap-1 hover:shadow-sm hover:-translate-y-0.5"
                        >
                          <Zap className="w-3 h-3" />
                          {tag}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 搜索面板和结果 */}
        <div className="grid grid-cols-1 lg:grid-cols-[400px_1fr] gap-6 lg:gap-8">
          {/* 搜索面板 */}
          <div className="space-y-6 order-2 lg:order-1">
            <SimilaritySearchPanel
              query={query}
              selectedThreshold={selectedThreshold}
              config={configState.config}
              suggestions={suggestionsState.suggestions}
              showSuggestions={suggestionsState.showSuggestions}
              isSearching={searchState.isSearching}
              onQueryChange={setQuery}
              onThresholdChange={setThreshold}
              onSearch={handleSearch}
              onSuggestionSelect={handleSuggestionSelect}
              onSuggestionsToggle={setShowSuggestions}
            />
          </div>

          {/* 搜索结果 */}
          <div className="min-h-[400px] sm:min-h-[600px] order-1 lg:order-2">
            {searchState.results.length > 0 ? (
              <SimilaritySearchResults
                results={searchState.results}
                totalResults={searchState.totalResults}
                currentPage={searchState.currentPage}
                maxResultsPerPage={configState.config?.max_results_per_page || 12}
                isLoading={searchState.isSearching}
                onPageChange={() => {}} // 暂时不实现分页
                onResultSelect={(result) => {
                  console.log('Selected result:', result);
                }}
              />
            ) : searchState.error ? (
              <div className="card h-full flex flex-col items-center justify-center text-center p-6 sm:p-12 animate-fade-in bg-gradient-to-br from-red-50 to-pink-50 border border-red-200">
                <div className="icon-container red w-16 h-16 mb-6 shadow-md">
                  <Search className="w-8 h-8" />
                </div>
                <h3 className="text-2xl font-bold text-red-900 mb-3">❌ 搜索出错了</h3>
                <p className="text-red-700 mb-6 max-w-md leading-relaxed">{searchState.error}</p>
                <button
                  onClick={handleReset}
                  className="btn btn-primary hover:shadow-md transition-all duration-200"
                >
                  🔄 重新开始
                </button>
              </div>
            ) : (
              <div className="card h-full flex flex-col items-center justify-center text-center p-6 sm:p-12 animate-fade-in bg-gradient-to-br from-purple-50 to-indigo-50 border border-purple-200">
                <div className="icon-container purple w-16 h-16 mb-6 shadow-md">
                  <TrendingUp className="w-8 h-8" />
                </div>
                <h3 className="text-2xl font-bold text-purple-900 mb-3">✨ 准备就绪</h3>
                <div className="space-y-2 text-purple-700 max-w-md">
                  <p className="flex items-center justify-center gap-2">
                    <Search className="w-4 h-4" />
                    输入关键词开始搜索
                  </p>
                  <p className="flex items-center justify-center gap-2">
                    <Zap className="w-4 h-4" />
                    或选择快速标签快速开始
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default SimilaritySearchTool;
