import { useState, useCallback, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { 
  Search, 
  Users, 
  Shield, 
  UserCog,
  Loader2,
  CheckCircle,
  AlertCircle,
  Crown,
  User as UserIcon
} from 'lucide-react';
import { userApi } from '@/services/userApi';

// Simple debounce function
function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null;
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null;
      func(...args);
    };
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

interface OktaUser {
  userId: string;
  email: string;
  firstName?: string;
  lastName?: string;
  displayName?: string;
  department?: string;
  phone?: string;
  mobilePhone?: string;
  designation?: string;
  jobTitle?: string;
  manager?: string;
  employeeId?: string;
  employeeNumber?: string;
  secondEmail?: string;
  location?: {
    state?: string;
    city?: string;
    country?: string;
    office?: string;
  };
}

interface UserWithRole {
  userId: string;
  email: string;
  displayName: string;
  role: 'USER' | 'MANAGEMENT' | 'ADMIN';
  department?: string;
  designation?: string;
}

export function UserRoleManager() {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<OktaUser[]>([]);
  const [searching, setSearching] = useState(false);
  const [selectedUser, setSelectedUser] = useState<OktaUser | null>(null);
  const [selectedRole, setSelectedRole] = useState<'USER' | 'MANAGEMENT' | 'ADMIN'>('USER');
  const [updating, setUpdating] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Users list with filtering and pagination
  const [users, setUsers] = useState<UserWithRole[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [roleStats, setRoleStats] = useState({ admins: 0, management: 0, users: 0 });
  
  // Pagination and filtering
  const [roleFilter, setRoleFilter] = useState<'ELEVATED' | 'ALL' | 'ADMIN' | 'MANAGEMENT' | 'USER'>('ELEVATED');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalUsers, setTotalUsers] = useState(0);
  const limit = 10;

  // Refs for search container and user list
  const searchContainerRef = useRef<HTMLDivElement>(null);
  const userListRef = useRef<HTMLDivElement>(null);

  // Search users from Okta
  const searchUsers = useCallback(
    debounce(async (query: string) => {
      // Only trigger search when using @ sign
      if (!query || !query.startsWith('@') || query.length < 2) {
        setSearchResults([]);
        setSearching(false);
        return;
      }

      setSearching(true);
      try {
        const term = query.slice(1); // Remove @ prefix
        const response = await userApi.searchUsers(term, 20);
        
        // Backend returns { success: true, data: [...users], message, timestamp }
        // Axios response is in response.data, actual user array is in response.data.data
        const users = response.data?.data || [];
        
        setSearchResults(users);
      } catch (error: any) {
        console.error('Search failed:', error);
        setMessage({
          type: 'error',
          text: error.response?.data?.message || 'Failed to search users'
        });
      } finally {
        setSearching(false);
      }
    }, 300),
    []
  );

  // Handle search input
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const query = e.target.value;
    setSearchQuery(query);
    searchUsers(query);
  };

  // Select user from search results
  const handleSelectUser = async (user: OktaUser) => {
    setSelectedUser(user);
    setSearchQuery(user.email);
    setSearchResults([]);
    
    // Check if user already exists in the current users list and has a role assigned
    const existingUser = users.find(u => 
      u.email.toLowerCase() === user.email.toLowerCase() || 
      u.userId === user.userId
    );
    
    if (existingUser && existingUser.role) {
      // Pre-select the user's current role
      setSelectedRole(existingUser.role);
    } else {
      // If user doesn't exist in current list, check all users in database
      try {
        const allUsers = await userApi.getAllUsers();
        const foundUser = allUsers.find((u: any) => 
          (u.email && u.email.toLowerCase() === user.email.toLowerCase()) || 
          (u.userId && u.userId === user.userId)
        );
        
        if (foundUser && foundUser.role) {
          setSelectedRole(foundUser.role);
        } else {
          // Default to USER if user doesn't exist
          setSelectedRole('USER');
        }
      } catch (error) {
        console.error('Failed to check user role:', error);
        // Default to USER on error
        setSelectedRole('USER');
      }
    }
  };

  // Assign role to user
  const handleAssignRole = async () => {
    if (!selectedUser || !selectedRole) {
      setMessage({ type: 'error', text: 'Please select a user and role' });
      return;
    }

    setUpdating(true);
    setMessage(null);

    try {
      // Call backend to assign role (will create user if doesn't exist)
      // Backend will fetch user data from Okta if user doesn't exist
      await userApi.assignRole(selectedUser.email, selectedRole);
      
      setMessage({
        type: 'success',
        text: `Successfully assigned ${selectedRole} role to ${selectedUser.displayName || selectedUser.email}`
      });

      // Reset form
      setSelectedUser(null);
      setSearchQuery('');
      setSelectedRole('USER');

      // Refresh the users list
      await fetchUsers();
      await fetchRoleStatistics();
    } catch (error: any) {
      console.error('Role assignment failed:', error);
      setMessage({
        type: 'error',
        text: error.response?.data?.error || 'Failed to assign role'
      });
    } finally {
      setUpdating(false);
    }
  };

  // Fetch users with filtering and pagination
  const fetchUsers = async (page: number = currentPage) => {
    setLoadingUsers(true);
    try {
      const response = await userApi.getUsersByRole(roleFilter, page, limit);

      // Backend returns { success: true, data: { users: [...], pagination: {...}, summary: {...} } }
      const usersData = response.data?.data?.users || [];
      const paginationData = response.data?.data?.pagination;
      const summaryData = response.data?.data?.summary;

      setUsers(usersData);
      
      if (paginationData) {
        setCurrentPage(paginationData.currentPage);
        setTotalPages(paginationData.totalPages);
        setTotalUsers(paginationData.totalUsers);
      }
      
      // Update summary stats if available
      if (summaryData) {
        setRoleStats({
          admins: summaryData.ADMIN || 0,
          management: summaryData.MANAGEMENT || 0,
          users: summaryData.USER || 0
        });
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
    } finally {
      setLoadingUsers(false);
    }
  };

  // Fetch role statistics
  const fetchRoleStatistics = async () => {
    try {
      const response = await userApi.getRoleStatistics();
      
      // Handle different response formats
      const statsData = response.data?.data?.statistics || response.data?.statistics || [];
      
      setRoleStats({
        admins: parseInt(statsData.find((s: any) => s.role === 'ADMIN')?.count || '0'),
        management: parseInt(statsData.find((s: any) => s.role === 'MANAGEMENT')?.count || '0'),
        users: parseInt(statsData.find((s: any) => s.role === 'USER')?.count || '0')
      });
    } catch (error) {
      console.error('Failed to fetch statistics:', error);
    }
  };

  // Load data on mount and when filter changes
  useEffect(() => {
    fetchUsers(1); // Reset to page 1 when filter changes
    fetchRoleStatistics();
  }, [roleFilter]);

  // Handle filter change
  const handleFilterChange = (value: string) => {
    setRoleFilter(value as any);
    setCurrentPage(1);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchUsers(page);
  };

  // Handle statistics card click - filter and scroll to user list
  const handleStatCardClick = (filter: 'ADMIN' | 'MANAGEMENT' | 'USER') => {
    setRoleFilter(filter);
    setCurrentPage(1);
    
    // Immediate scroll without waiting for data load
    requestAnimationFrame(() => {
      const element = userListRef.current;
      if (element) {
        element.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'start'
        });
      }
    });
  };

  // Handle click outside to close search results
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchContainerRef.current && !searchContainerRef.current.contains(event.target as Node)) {
        setSearchResults([]);
      }
    };

    if (searchResults.length > 0) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [searchResults]);

  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return 'bg-yellow-400 text-slate-800';
      case 'MANAGEMENT':
        return 'bg-blue-400 text-slate-800';
      default:
        return 'bg-gray-400 text-slate-800';
    }
  };

  const getRoleIcon = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return <Crown className="w-5 h-5 text-slate-800" />;
      case 'MANAGEMENT':
        return <Users className="w-5 h-5 text-slate-800" />;
      default:
        return <UserIcon className="w-5 h-5 text-slate-800" />;
    }
  };

  return (
    <Card className="shadow-lg border-0 rounded-md">
      <CardHeader className="pb-4">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md">
            <UserCog className="h-5 w-5 text-white" />
          </div>
          <div>
            <CardTitle className="text-lg font-semibold text-gray-900">User Role Management</CardTitle>
            <CardDescription className="text-sm text-gray-600">
              Search for users, assign roles, and manage user permissions across the system
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Statistics Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6">
        <Card 
          className={`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${
            roleFilter === 'ADMIN' ? 'border-yellow-400 shadow-lg' : 'border-transparent shadow-md'
          }`}
          data-testid="admin-count-card"
          onClick={() => handleStatCardClick('ADMIN')}
        >
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-600 uppercase tracking-wide">Administrators</p>
                <p className="text-3xl font-bold text-gray-900 mt-2" data-testid="admin-count">{roleStats.admins}</p>
                <p className="text-xs text-yellow-700 mt-1 font-semibold">
                  {roleFilter === 'ADMIN' ? '✓ Viewing' : 'Click to view'}
                </p>
              </div>
              <div className="p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md">
                <Crown className="w-6 h-6 text-slate-800" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card 
          className={`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${
            roleFilter === 'MANAGEMENT' ? 'border-blue-400 shadow-lg' : 'border-transparent shadow-md'
          }`}
          data-testid="management-count-card"
          onClick={() => handleStatCardClick('MANAGEMENT')}
        >
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-600 uppercase tracking-wide">Management</p>
                <p className="text-3xl font-bold text-gray-900 mt-2" data-testid="management-count">{roleStats.management}</p>
                <p className="text-xs text-blue-700 mt-1 font-semibold">
                  {roleFilter === 'MANAGEMENT' ? '✓ Viewing' : 'Click to view'}
                </p>
              </div>
              <div className="p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md">
                <Users className="w-6 h-6 text-slate-800" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card 
          className={`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${
            roleFilter === 'USER' ? 'border-gray-400 shadow-lg' : 'border-transparent shadow-md'
          }`}
          data-testid="user-count-card"
          onClick={() => handleStatCardClick('USER')}
        >
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-600 uppercase tracking-wide">Regular Users</p>
                <p className="text-3xl font-bold text-gray-900 mt-2" data-testid="user-count">{roleStats.users}</p>
                <p className="text-xs text-gray-700 mt-1 font-semibold">
                  {roleFilter === 'USER' ? '✓ Viewing' : 'Click to view'}
                </p>
              </div>
              <div className="p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md">
                <UserIcon className="w-6 h-6 text-slate-800" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Separator />

      {/* Assign Role Section */}
      <div className="space-y-5">
        <div>
          <h3 className="text-base font-semibold text-gray-900 mb-1">Assign User Role</h3>
          <p className="text-sm text-gray-600">
            Search for a user in Okta and assign them a role
          </p>
        </div>
        <div className="space-y-5">
          {/* Search Input */}
          <div className="space-y-2" ref={searchContainerRef}>
            <label className="text-sm font-medium text-gray-700">Search User</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
              <Input
                type="text"
                placeholder="Type @ to search users..."
                value={searchQuery}
                onChange={handleSearchChange}
                className="pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"
                data-testid="user-search-input"
              />
              {searching && (
                <Loader2 className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin" />
              )}
            </div>
            <p className="text-xs text-gray-500">Start with @ to search users (e.g., @john)</p>

            {/* Search Results Dropdown */}
            {searchResults.length > 0 && (
              <div className="border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto">
                <div className="sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100">
                  <p className="text-xs font-semibold text-purple-700">
                    {searchResults.length} user{searchResults.length > 1 ? 's' : ''} found
                  </p>
                </div>
                <div className="p-2">
                  {searchResults.map((user) => (
                    <button
                      key={user.userId}
                      onClick={() => handleSelectUser(user)}
                      className="w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0"
                      data-testid={`user-result-${user.email}`}
                    >
                      <p className="text-sm font-medium text-gray-900">{user.displayName || user.email}</p>
                      <p className="text-xs text-gray-600">{user.email}</p>
                      {user.department && (
                        <p className="text-xs text-gray-500">
                          {user.department}{user.designation ? ` • ${user.designation}` : ''}
                        </p>
                      )}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Selected User */}
          {selectedUser && (
            <div className="border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md">
                    {(selectedUser.displayName || selectedUser.email).charAt(0).toUpperCase()}
                  </div>
                  <div>
                    <p className="font-semibold text-slate-900">
                      {selectedUser.displayName || selectedUser.email}
                    </p>
                    <p className="text-sm text-slate-600">{selectedUser.email}</p>
                    {selectedUser.department && (
                      <p className="text-xs text-slate-500 mt-1">
                        {selectedUser.department}{selectedUser.designation ? ` • ${selectedUser.designation}` : ''}
                      </p>
                    )}
                  </div>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setSelectedUser(null);
                    setSearchQuery('');
                  }}
                  className="hover:bg-slate-200"
                >
                  Clear
                </Button>
              </div>
            </div>
          )}

          {/* Role Selection */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">Select Role</label>
            <Select value={selectedRole} onValueChange={(value: any) => setSelectedRole(value)}>
              <SelectTrigger 
                className="border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"
                data-testid="role-select"
              >
                <SelectValue placeholder="Select role" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="USER">
                  <div className="flex items-center gap-2">
                    <UserIcon className="w-4 h-4 text-gray-600" />
                    <span>User - Regular access</span>
                  </div>
                </SelectItem>
                <SelectItem value="MANAGEMENT">
                  <div className="flex items-center gap-2">
                    <Users className="w-4 h-4 text-blue-600" />
                    <span>Management - Read all data</span>
                  </div>
                </SelectItem>
                <SelectItem value="ADMIN">
                  <div className="flex items-center gap-2">
                    <Crown className="w-4 h-4 text-yellow-600" />
                    <span>Administrator - Full access</span>
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Assign Button */}
          <Button
            onClick={handleAssignRole}
            disabled={!selectedUser || updating}
            className="w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            data-testid="assign-role-button"
          >
            {updating ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Assigning Role...
              </>
            ) : (
              <>
                <Shield className="w-4 h-4 mr-2" />
                Assign Role
              </>
            )}
          </Button>

          {/* Message */}
          {message && (
            <div className={`border-2 rounded-lg p-4 ${
              message.type === 'success' 
                ? 'border-green-200 bg-green-50' 
                : 'border-red-200 bg-red-50'
            }`}>
              <div className="flex items-start gap-3">
                {message.type === 'success' ? (
                  <CheckCircle className="w-5 h-5 text-green-600 shrink-0 mt-0.5" />
                ) : (
                  <AlertCircle className="w-5 h-5 text-red-600 shrink-0 mt-0.5" />
                )}
                <p className={`text-sm ${message.type === 'success' ? 'text-green-800' : 'text-red-800'}`}>
                  {message.text}
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      <Separator />

      {/* Users List with Filter and Pagination */}
      <div ref={userListRef}>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
          <div>
            <h3 className="text-base font-semibold text-gray-900 mb-1">User Management</h3>
            <p className="text-sm text-gray-600">
              View and manage user roles ({totalUsers} {roleFilter !== 'ALL' && roleFilter !== 'ELEVATED' ? roleFilter.toLowerCase() : ''} users)
            </p>
          </div>
            <div className="flex items-center gap-3">
              <Select value={roleFilter} onValueChange={handleFilterChange}>
                <SelectTrigger className="w-[200px] h-10 border rounded-lg border-gray-300">
                  <SelectValue placeholder="Filter by role" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ELEVATED">
                    <div className="flex items-center gap-2">
                      <Shield className="w-4 h-4 text-purple-600" />
                      <span>Elevated ({roleStats.admins + roleStats.management})</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="ADMIN">
                    <div className="flex items-center gap-2">
                      <Crown className="w-4 h-4 text-yellow-600" />
                      <span>Admins ({roleStats.admins})</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="MANAGEMENT">
                    <div className="flex items-center gap-2">
                      <Users className="w-4 h-4 text-blue-600" />
                      <span>Management ({roleStats.management})</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="USER">
                    <div className="flex items-center gap-2">
                      <UserIcon className="w-4 h-4 text-gray-600" />
                      <span>Users ({roleStats.users})</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="ALL">
                    <div className="flex items-center gap-2">
                      <Users className="w-4 h-4 text-gray-600" />
                      <span>All Users ({roleStats.admins + roleStats.management + roleStats.users})</span>
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        <div className="pt-2">
          {loadingUsers ? (
            <div className="flex flex-col items-center justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-purple-500 mb-2" />
              <p className="text-sm text-gray-500">Loading users...</p>
            </div>
          ) : users.length === 0 ? (
            <div className="text-center py-8">
              <div className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3">
                <Users className="w-6 h-6 text-gray-400" />
              </div>
              <p className="font-medium text-gray-700">No users found</p>
              <p className="text-sm text-gray-500 mt-1">
                {roleFilter === 'ELEVATED' 
                  ? 'Assign ADMIN or MANAGEMENT roles to see users here'
                  : 'No users match the selected filter'
                }
              </p>
            </div>
          ) : (
            <>
              <div className="space-y-2" data-testid="users-list">
                {users.map((user) => (
                  <div 
                    key={user.userId} 
                    className="border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4"
                    data-testid={`user-${user.email}`}
                  >
                    <div className="flex items-center justify-between gap-4">
                      <div className="flex items-center gap-3 flex-1 min-w-0">
                        <div className={`w-10 h-10 rounded-lg ${getRoleBadgeColor(user.role)} flex items-center justify-center shadow-sm`}>
                          {getRoleIcon(user.role)}
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="font-semibold text-gray-900 truncate">{user.displayName}</p>
                          <p className="text-sm text-gray-600 truncate">{user.email}</p>
                          {user.department && (
                            <p className="text-xs text-gray-500 mt-1 truncate">
                              {user.department}{user.designation ? ` • ${user.designation}` : ''}
                            </p>
                          )}
                        </div>
                      </div>
                      <Badge className={`${getRoleBadgeColor(user.role)} shrink-0`} data-testid={`role-badge-${user.role}`}>
                        {user.role}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination Controls */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between pt-4 border-t">
                  <div className="text-sm text-gray-600">
                    Showing {((currentPage - 1) * limit) + 1} to {Math.min(currentPage * limit, totalUsers)} of {totalUsers} users
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handlePageChange(currentPage - 1)}
                      disabled={currentPage === 1}
                      data-testid="prev-page-button"
                    >
                      Previous
                    </Button>
                    <div className="flex items-center gap-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum;
                        if (totalPages <= 5) {
                          pageNum = i + 1;
                        } else if (currentPage <= 3) {
                          pageNum = i + 1;
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i;
                        } else {
                          pageNum = currentPage - 2 + i;
                        }
                        return (
                          <Button
                            key={pageNum}
                            variant={currentPage === pageNum ? "default" : "outline"}
                            size="sm"
                            onClick={() => handlePageChange(pageNum)}
                            className={`w-9 h-9 p-0 ${
                              currentPage === pageNum 
                                ? 'bg-re-green hover:bg-re-green/90 text-white' 
                                : ''
                            }`}
                            data-testid={`page-${pageNum}-button`}
                          >
                            {pageNum}
                          </Button>
                        );
                      })}
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handlePageChange(currentPage + 1)}
                      disabled={currentPage === totalPages}
                      data-testid="next-page-button"
                    >
                      Next
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
      </CardContent>
    </Card>
  );
}

