/**
 * filekorolheader: 分页组件 - 可配置的分页导航组件
 * 功能：分页导航、页码跳转、每页条数设置、分页信息显示
 * 路径：/components/common/searchFormPagination/components/PaginationComponent
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式，支持完全自定义配置
 */
'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight } from 'lucide-react';

// 分页配置接口
export interface PaginationConfig {
  page: number;
  size: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

// 组件Props接口
export interface PaginationComponentProps {
  pagination: PaginationConfig;
  onPageChange: (page: number) => void;
  onSizeChange?: (size: number) => void;
  loading?: boolean;
  showSizeSelector?: boolean;
  showPageInfo?: boolean;
  showQuickJumper?: boolean;
  sizeOptions?: number[];
  maxVisiblePages?: number;
  className?: string;
}

export function PaginationComponent({
  pagination,
  onPageChange,
  onSizeChange,
  loading = false,
  showSizeSelector = true,
  showPageInfo = true,
  showQuickJumper = false,
  sizeOptions = [10, 30, 50, 100],
  maxVisiblePages = 7,
  className = '',
}: PaginationComponentProps) {
  const [jumpPage, setJumpPage] = useState('');

  // 处理页码变化
  const handlePageChange = (page: number) => {
    // 边界检查
    if (page < 1) page = 1;
    if (page > pagination.totalPages && pagination.totalPages > 0) {
      page = pagination.totalPages;
    }
    onPageChange(page);
  };

  // 处理每页条数变化
  const handleSizeChange = (size: string) => {
    const newSize = parseInt(size, 10);
    onSizeChange?.(newSize);
  };

  // 处理快速跳转
  const handleJumpPage = () => {
    const page = parseInt(jumpPage, 10);
    if (!isNaN(page) && page >= 1 && page <= pagination.totalPages) {
      handlePageChange(page);
      setJumpPage('');
    }
  };

  // 处理跳转输入框回车
  const handleJumpKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleJumpPage();
    }
  };

  // 生成可见页码数组
  const generateVisiblePages = () => {
    const { page, totalPages } = pagination;
    const visiblePages: number[] = [];

    if (totalPages <= maxVisiblePages) {
      // 如果总页数少于最大可见页数，显示所有页码
      for (let i = 1; i <= totalPages; i++) {
        visiblePages.push(i);
      }
    } else {
      // 否则生成智能的页码显示范围
      const half = Math.floor(maxVisiblePages / 2);
      let start = Math.max(1, page - half);
      let end = Math.min(totalPages, start + maxVisiblePages - 1);

      // 调整开始位置，确保显示足够数量的页码
      if (end - start < maxVisiblePages - 1) {
        start = Math.max(1, end - maxVisiblePages + 1);
      }

      for (let i = start; i <= end; i++) {
        visiblePages.push(i);
      }
    }

    return visiblePages;
  };

  const visiblePages = generateVisiblePages();
  const { page, total, totalPages, hasPrev, hasNext } = pagination;

  return (
    <div className={`flex items-center justify-between mt-4 ${className}`}>
      {/* 左侧信息 */}
      <div className="flex items-center gap-4">
        {showPageInfo && (
          <div className="text-sm text-muted-foreground">
            显示第 {page} 页，共 {totalPages} 页
            <span className="ml-2">总计 {total} 条记录</span>
          </div>
        )}

        {showSizeSelector && onSizeChange && (
          <div className="flex items-center gap-2">
            <span className="text-sm text-muted-foreground">每页显示</span>
            <Select value={String(pagination.size)} onValueChange={handleSizeChange}>
              <SelectTrigger className="w-20">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {sizeOptions.map((size) => (
                  <SelectItem key={size} value={String(size)}>
                    {size}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <span className="text-sm text-muted-foreground">条</span>
          </div>
        )}
      </div>

      {/* 右侧分页导航 - 只有超过一页时才显示分页按钮 */}
      {totalPages > 1 && (
        <div className="flex items-center gap-2">
          {/* 上一页按钮 */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(page - 1)}
            disabled={!hasPrev || loading}
          >
            <ChevronLeft className="w-4 h-4" />
            上一页
          </Button>

          {/* 页码按钮 */}
          <div className="flex items-center gap-1">
            {visiblePages.map((pageNum) => (
              <Button
                key={pageNum}
                variant={pageNum === page ? 'default' : 'outline'}
                size="sm"
                onClick={() => handlePageChange(pageNum)}
                disabled={loading}
                className="min-w-[2.5rem]"
              >
                {pageNum}
              </Button>
            ))}
          </div>

          {/* 下一页按钮 */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(page + 1)}
            disabled={!hasNext || loading}
          >
            下一页
            <ChevronRight className="w-4 h-4" />
          </Button>

          {/* 快速跳转 */}
          {showQuickJumper && totalPages > 5 && (
            <div className="flex items-center gap-2 ml-4">
              <span className="text-sm text-muted-foreground">跳至</span>
              <Input
                type="number"
                min={1}
                max={totalPages}
                value={jumpPage}
                onChange={(e) => setJumpPage(e.target.value)}
                onKeyPress={handleJumpKeyPress}
                placeholder="页码"
                className="w-16 h-8"
                disabled={loading}
              />
              <span className="text-sm text-muted-foreground">页</span>
              <Button
                variant="outline"
                size="sm"
                onClick={handleJumpPage}
                disabled={loading || !jumpPage}
              >
                确定
              </Button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default PaginationComponent;