import React, { useCallback } from 'react';
import {
  ChevronLeft,
  ChevronRight,
  MoreHorizontal,
} from 'lucide-react';
import { MaterialSearchPaginationProps } from '../../types/outfitRecommendation';

/**
 * 素材检索分页组件
 * 遵循 Tauri 开发规范的组件设计模式
 */
const MaterialSearchPagination: React.FC<MaterialSearchPaginationProps> = ({
  currentPage,
  totalPages,
  pageSize,
  totalSize,
  isLoading = false,
  onPageChange,
  onPageSizeChange,
  className = '',
}) => {
  // 计算显示的页码范围
  const getVisiblePages = useCallback(() => {
    const delta = 2; // 当前页前后显示的页数
    const range = [];
    const rangeWithDots = [];

    // 如果总页数较少，显示所有页码
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) {
        range.push(i);
      }
      return range;
    }

    // 计算显示范围
    for (let i = Math.max(2, currentPage - delta); i <= Math.min(totalPages - 1, currentPage + delta); i++) {
      range.push(i);
    }

    // 添加第一页
    if (currentPage - delta > 2) {
      rangeWithDots.push(1, '...');
    } else {
      rangeWithDots.push(1);
    }

    // 添加中间页码
    rangeWithDots.push(...range);

    // 添加最后一页
    if (currentPage + delta < totalPages - 1) {
      rangeWithDots.push('...', totalPages);
    } else if (totalPages > 1) {
      rangeWithDots.push(totalPages);
    }

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

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

  // 处理每页大小变化
  const handlePageSizeChange = useCallback((newPageSize: number) => {
    if (onPageSizeChange && newPageSize !== pageSize) {
      onPageSizeChange(newPageSize);
    }
  }, [pageSize, onPageSizeChange]);

  // 计算显示信息
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalSize);
  const visiblePages = getVisiblePages();

  if (totalPages <= 1) {
    return null;
  }

  return (
    <div className={`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 ${className}`}>
      {/* 分页信息和每页显示数量 */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
        <div className="text-sm text-medium-emphasis">
          显示 {startItem} 到 {endItem} 项，共 {totalSize} 项
        </div>
        
        {onPageSizeChange && (
          <div className="flex items-center gap-2">
            <span className="text-sm text-medium-emphasis">每页显示:</span>
            <select
              value={pageSize}
              onChange={(e) => handlePageSizeChange(Number(e.target.value))}
              disabled={isLoading}
              className="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <option value={6}>6 项</option>
              <option value={9}>9 项</option>
              <option value={12}>12 项</option>
              <option value={18}>18 项</option>
              <option value={24}>24 项</option>
            </select>
          </div>
        )}
      </div>

      {/* 分页控制 */}
      <div className="flex items-center gap-1">
        {/* 上一页按钮 */}
        <button
          onClick={() => handlePageChange(currentPage - 1)}
          disabled={currentPage === 1 || isLoading}
          aria-label="上一页"
          className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent focus:ring-2 focus:ring-primary-500 focus:outline-none"
        >
          <ChevronLeft className="w-4 h-4" />
          <span className="hidden sm:inline">上一页</span>
        </button>

        {/* 页码按钮 */}
        <div className="flex items-center gap-1">
          {visiblePages.map((page, index) => {
            if (page === '...') {
              return (
                <div
                  key={`dots-${index}`}
                  className="flex items-center justify-center w-10 h-10 text-gray-400"
                >
                  <MoreHorizontal className="w-4 h-4" />
                </div>
              );
            }

            const pageNumber = page as number;
            const isCurrentPage = pageNumber === currentPage;

            return (
              <button
                key={pageNumber}
                onClick={() => handlePageChange(pageNumber)}
                disabled={isLoading}
                className={`
                  w-10 h-10 rounded-lg font-medium text-sm transition-all duration-200
                  ${isCurrentPage
                    ? 'bg-gradient-primary text-white shadow-lg shadow-primary-500/25'
                    : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
                  }
                  disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent
                `}
              >
                {pageNumber}
              </button>
            );
          })}
        </div>

        {/* 下一页按钮 */}
        <button
          onClick={() => handlePageChange(currentPage + 1)}
          disabled={currentPage === totalPages || isLoading}
          aria-label="下一页"
          className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent focus:ring-2 focus:ring-primary-500 focus:outline-none"
        >
          <span className="hidden sm:inline">下一页</span>
          <ChevronRight className="w-4 h-4" />
        </button>
      </div>

      {/* 快速跳转（可选） */}
      {totalPages > 10 && (
        <div className="flex items-center gap-2">
          <span className="text-sm text-medium-emphasis">跳转到:</span>
          <input
            type="number"
            min={1}
            max={totalPages}
            value={currentPage}
            onChange={(e) => {
              const page = parseInt(e.target.value);
              if (page >= 1 && page <= totalPages) {
                handlePageChange(page);
              }
            }}
            disabled={isLoading}
            className="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
          />
          <span className="text-sm text-medium-emphasis">页</span>
        </div>
      )}
    </div>
  );
};

export default MaterialSearchPagination;
