import React, { useCallback } from 'react';
import { createPortal } from 'react-dom';
import {
  Grid,
  TrendingUp,
  ExternalLink,
  ChevronRight,
  ChevronLeft,
  Loader2
} from 'lucide-react';
import { SimilaritySearchResultsProps } from '../../types/similaritySearch';
import { SimilaritySearchCard } from './SimilaritySearchCard'
import SimilaritySearchService from '../../services/similaritySearchService';

/**
 * 相似度检索结果展示组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const SimilaritySearchResults: React.FC<SimilaritySearchResultsProps> = ({
  results,
  totalResults,
  currentPage,
  maxResultsPerPage,
  isLoading,
  onPageChange,
  onPageSizeChange,
  onResultSelect,
  onExternalLinkClick,
}) => {
  // 计算分页信息
  const totalPages = SimilaritySearchService.getTotalPages(totalResults, maxResultsPerPage);
  const pageInfo = SimilaritySearchService.getPageRangeInfo(currentPage, maxResultsPerPage, totalResults);

  // 生成智能分页数字
  const generatePageNumbers = useCallback(() => {
    const pages: (number | string)[] = [];
    const maxVisible = 7; // 最多显示7个页码按钮

    if (totalPages <= maxVisible) {
      // 总页数少，显示所有页码
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // 总页数多，智能显示
      pages.push(1); // 始终显示第一页

      if (currentPage <= 4) {
        // 当前页在前面
        for (let i = 2; i <= 5; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      } else if (currentPage >= totalPages - 3) {
        // 当前页在后面
        pages.push('...');
        for (let i = totalPages - 4; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        // 当前页在中间
        pages.push('...');
        for (let i = currentPage - 1; i <= currentPage + 1; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      }
    }

    return pages;
  }, [currentPage, totalPages]);

  // 处理结果选择
  const handleResultSelect = useCallback((result: any) => {
    if (onResultSelect) {
      onResultSelect(result);
    }
  }, [onResultSelect]);

  // 处理每页显示数量变化
  const handlePageSizeChange = useCallback((newPageSize: number) => {
    if (onPageSizeChange) {
      onPageSizeChange(newPageSize);
    }
  }, [onPageSizeChange]);

  // 每页显示数量选项
  const pageSizeOptions = [6, 12, 24, 48, 96];



  if (isLoading) {
    return (
      <div className="card h-full flex flex-col items-center justify-center p-8 animate-fade-in">
        <div className="icon-container primary w-16 h-16 mb-6">
          <TrendingUp className="w-8 h-8 animate-pulse" />
        </div>
        <h3 className="text-xl font-semibold text-high-emphasis mb-2">正在搜索...</h3>
        <p className="text-medium-emphasis">AI正在为您寻找最相似的内容</p>
        
        {/* 加载动画 */}
        <div className="mt-6 flex space-x-2">
          {[0, 1, 2].map((i) => (
            <div
              key={i}
              className="w-2 h-2 bg-primary-500 rounded-full animate-bounce"
              style={{ animationDelay: `${i * 0.1}s` }}
            ></div>
          ))}
        </div>
      </div>
    );
  }

  if (results.length === 0) {
    return (
      <div className="card h-full flex flex-col items-center justify-center text-center p-8 animate-fade-in">
        <div className="icon-container gray w-16 h-16 mb-6">
          <Grid className="w-8 h-8" />
        </div>
        <h3 className="text-xl font-semibold text-high-emphasis mb-2">暂无搜索结果</h3>
        <p className="text-medium-emphasis max-w-md">
          没有找到匹配的内容，请尝试：
        </p>
        <ul className="text-sm text-medium-emphasis mt-3 space-y-1">
          <li>• 使用不同的关键词</li>
          <li>• 降低相关性阈值</li>
          <li>• 尝试更通用的搜索词</li>
        </ul>
      </div>
    );
  }

  return (
    <div className="relative space-y-6 animate-fade-in">
      {/* 加载遮罩 */}
      {isLoading && (
        <div className="absolute inset-0 bg-white/80 backdrop-blur-sm z-10 flex items-center justify-center rounded-lg">
          <div className="flex flex-col items-center gap-3 p-6">
            <Loader2 className="w-8 h-8 animate-spin text-primary-600" />
            <div className="text-center">
              <p className="text-sm font-medium text-gray-900">正在搜索...</p>
              <p className="text-xs text-gray-600 mt-1">请稍候，正在为您查找相似内容</p>
            </div>
          </div>
        </div>
      )}

      {/* 结果统计 */}
      <div className="card p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="icon-container green w-8 h-8 shadow-sm">
              <TrendingUp className="w-4 h-4" />
            </div>
            <div>
              <h3 className="text-sm font-semibold text-green-900">
                🎯 找到 {totalResults} 个相似结果
              </h3>
              <p className="text-xs text-green-700">
                显示第 {pageInfo.start}-{pageInfo.end} 个结果
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* 结果网格 */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-4 lg:gap-6">
        {results.map((result, index) => (
          <SimilaritySearchCard
            key={result.id || index}
            result={result}
            onSelect={handleResultSelect}
            onExternalLinkClick={onExternalLinkClick}
            showScore={true}
            compact={true}
          />
        ))}
      </div>

      {/* 分页控制 */}
      {totalPages > 1 && (
        <div className="card p-4">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            {/* 分页信息和每页显示数量 */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
              <div className="text-sm text-medium-emphasis">
                第 {currentPage} 页，共 {totalPages} 页 (总计 {totalResults} 条)
              </div>

              {onPageSizeChange && (
                <div className="flex items-center gap-2 text-sm">
                  <span className="text-medium-emphasis">每页</span>
                  <select
                    value={maxResultsPerPage}
                    onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                    disabled={isLoading}
                    className="px-2 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {pageSizeOptions.map(size => (
                      <option key={size} value={size}>{size} 条</option>
                    ))}
                  </select>
                  {isLoading && (
                    <div className="flex items-center gap-1 text-primary-600">
                      <Loader2 className="w-3 h-3 animate-spin" />
                      <span className="text-xs">更新中...</span>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 分页按钮 */}
            <div className="flex items-center gap-2">
              <button
                onClick={() => onPageChange(currentPage - 1)}
                disabled={currentPage <= 1 || isLoading}
                className="btn btn-secondary btn-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading && currentPage > 1 ? (
                  <div className="flex items-center gap-1">
                    <Loader2 className="w-3 h-3 animate-spin" />
                    <span>上一页</span>
                  </div>
                ) : (
                  '上一页'
                )}
              </button>

              <div className="flex items-center gap-1">
                {generatePageNumbers().map((page, index) => {
                  if (page === '...') {
                    return (
                      <span key={`ellipsis-${index}`} className="px-2 py-1 text-gray-400">
                        ...
                      </span>
                    );
                  }

                  const pageNum = page as number;
                  return (
                    <button
                      key={pageNum}
                      onClick={() => onPageChange(pageNum)}
                      disabled={isLoading}
                      className={`min-w-[32px] h-8 px-2 text-sm rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed ${
                        currentPage === pageNum
                          ? 'bg-primary-500 text-white shadow-md'
                          : 'text-gray-600 hover:bg-gray-100 border border-gray-200'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
              </div>

              <button
                onClick={() => onPageChange(currentPage + 1)}
                disabled={currentPage >= totalPages || isLoading}
                className="btn btn-secondary btn-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading && currentPage < totalPages ? (
                  <div className="flex items-center gap-1">
                    <Loader2 className="w-3 h-3 animate-spin" />
                    <span>下一页</span>
                  </div>
                ) : (
                  '下一页'
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 结果操作提示 */}
      <div className="card p-4 bg-blue-50 border-blue-200">
        <div className="flex items-start gap-3">
          <div className="icon-container blue w-6 h-6 mt-0.5">
            <ExternalLink className="w-3 h-3" />
          </div>
          <div className="flex-1">
            <h4 className="text-sm font-medium text-blue-900 mb-1">操作提示</h4>
            <p className="text-xs text-blue-700">
              点击结果卡片查看详细信息，或使用外部链接在新窗口中打开
            </p>
          </div>
        </div>
      </div>

      {/* 悬浮分页按钮组 - 使用 Portal 确保真正固定在屏幕上 */}
      {results.length > 0 && totalPages > 1 && createPortal(
        <div className="fixed top-1/2 transform -translate-y-1/2 z-[9999] pointer-events-none">
          {/* 上一页按钮 - 左侧 */}
          {currentPage > 1 && (
            <button
              onClick={() => onPageChange(currentPage - 1)}
              className="fixed left-4 w-10 h-10 bg-white/90 backdrop-blur-sm border border-gray-200/50 rounded-full shadow-md hover:shadow-lg transition-all duration-300 flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-white hover:border-gray-300 opacity-70 hover:opacity-100 pointer-events-auto"
              title={`上一页 (${currentPage - 1}/${totalPages})`}
              style={{
                position: 'fixed',
                left: '16px',
                top: '50%',
                transform: 'translateY(-50%)',
              }}
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
          )}

          {/* 下一页按钮 - 右侧 */}
          {currentPage < totalPages && (
            <button
              onClick={() => onPageChange(currentPage + 1)}
              className="fixed right-4 w-10 h-10 bg-white/90 backdrop-blur-sm border border-gray-200/50 rounded-full shadow-md hover:shadow-lg transition-all duration-300 flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-white hover:border-gray-300 opacity-70 hover:opacity-100 pointer-events-auto"
              title={`下一页 (${currentPage + 1}/${totalPages})`}
              style={{
                position: 'fixed',
                right: '16px',
                top: '50%',
                transform: 'translateY(-50%)',
              }}
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          )}
        </div>,
        document.body
      )}
    </div>
  );
};

export default SimilaritySearchResults;
