import React, { useCallback } from 'react';
import { SearchResultsProps } from '../../types/outfitSearch';
import { OutfitCard } from './OutfitCard';
import OutfitSearchService from '../../services/outfitSearchService';
import { Search, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';

/**
 * 搜索结果展示组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const SearchResults: React.FC<SearchResultsProps> = ({
  results,
  totalSize,
  currentPage,
  pageSize,
  onPageChange,
  onItemSelect,
  isLoading,
}) => {
  // 计算分页信息
  const totalPages = OutfitSearchService.getTotalPages(totalSize, pageSize);
  const hasNextPage = OutfitSearchService.hasMoreResults(
    { results, total_size: totalSize } as any,
    currentPage,
    pageSize
  );
  const hasPreviousPage = currentPage > 1;

  // 处理页面变化
  const handlePageChange = useCallback((page: number) => {
    if (page >= 1 && page <= totalPages) {
      onPageChange(page);
    }
  }, [totalPages, onPageChange]);

  // 生成页码数组
  const getPageNumbers = useCallback(() => {
    const pages: number[] = [];
    const maxVisiblePages = 5;
    
    if (totalPages <= maxVisiblePages) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      const start = Math.max(1, currentPage - 2);
      const end = Math.min(totalPages, start + maxVisiblePages - 1);
      
      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
    }
    
    return pages;
  }, [currentPage, totalPages]);

  if (isLoading) {
    return (
      <div className="card h-96 flex items-center justify-center animate-fade-in">
        <div className="text-center space-y-4">
          <div className="flex justify-center">
            <Loader2 className="w-12 h-12 text-primary-500 animate-spin" />
          </div>
          <p className="text-lg font-medium text-gray-600">正在搜索中...</p>
          <p className="text-sm text-gray-400">AI正在为您寻找最佳搭配</p>
        </div>
      </div>
    );
  }

  if (results.length === 0) {
    return (
      <div className="card h-96 flex items-center justify-center animate-fade-in">
        <div className="text-center space-y-6 max-w-md">
          <div className="flex justify-center">
            <div className="icon-container gray w-20 h-20">
              <Search className="w-10 h-10" />
            </div>
          </div>
          <div className="space-y-3">
            <h3 className="text-heading-3 text-high-emphasis">未找到相关结果</h3>
            <p className="text-body text-medium-emphasis">
              尝试调整搜索关键词或筛选条件，或者上传图片进行AI分析
            </p>
          </div>
          <div className="flex flex-wrap gap-2 justify-center">
            <span className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">休闲搭配</span>
            <span className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">正式风格</span>
            <span className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">牛仔裤</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 结果统计 - 现代化设计 */}
      <div className="card p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
              <span className="text-sm font-medium text-gray-900">
                找到 <span className="text-primary-600">{totalSize}</span> 个结果
              </span>
            </div>
            <div className="h-4 w-px bg-gray-300" />
            <span className="text-sm text-gray-500">
              第 {currentPage} 页，共 {totalPages} 页
            </span>
          </div>
        </div>
      </div>

      {/* 结果网格 - 响应式布局 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {results.map((result, index) => (
          <div key={result.id || index} className="animate-slide-in-up" style={{ animationDelay: `${index * 100}ms` }}>
            <OutfitCard
              result={result}
              onSelect={onItemSelect}
              showScore={true}
            />
          </div>
        ))}
      </div>

      {/* 分页控件 - 现代化设计 */}
      {totalPages > 1 && (
        <div className="card p-4">
          <div className="flex items-center justify-center gap-2">
            <button
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={!hasPreviousPage}
              className="btn btn-secondary btn-sm hover-lift disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ChevronLeft className="w-4 h-4" />
              上一页
            </button>

            <div className="flex items-center gap-1 mx-4">
              {getPageNumbers().map((page) => (
                <button
                  key={page}
                  onClick={() => handlePageChange(page)}
                  className={`w-10 h-10 rounded-lg font-medium text-sm transition-all duration-200 hover-lift ${
                    page === currentPage
                      ? 'bg-gradient-primary text-white shadow-lg shadow-primary-500/25'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  {page}
                </button>
              ))}
            </div>

            <button
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={!hasNextPage}
              className="btn btn-secondary btn-sm hover-lift disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}
    </div>

  );
};

export default SearchResults;
