"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Skeleton } from "@/components/ui/skeleton"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import {
  Search,
  Loader2,
  RefreshCw,
  CheckCircle,
  XCircle,
  Clock,
  Star,
  MapPin,
  Building,
  Eye,
  MoreVertical,
  Trash2,
  CheckSquare,
  XSquare,
  Edit,
  Phone,
  Mail,
  Calendar,
  User,
  FileText,
  ShieldCheck,
  Download,
  Users,
  Building2,
  Heart,
  MessageSquare,
  Ban,
  Shield,
  AlertTriangle,
  Activity
} from "lucide-react"

import { useSearchParams } from "next/navigation"

export default function AdminUsersPage() {
  const toast = useToast()
  const searchParams = useSearchParams()

  // Data states
  const [users, setUsers] = useState<any[]>([])
  const [stats, setStats] = useState({ total: 0, active: 0, pending: 0, suspended: 0, family: 0, facilityOwners: 0, verified: 0 })
  const [selectedUser, setSelectedUser] = useState<any | null>(null)

  // Loading states
  const [loading, setLoading] = useState(true)
  const [statsLoading, setStatsLoading] = useState(true)
  const [actionLoading, setActionLoading] = useState(false)
  const [isLoadingUserDetails, setIsLoadingUserDetails] = useState(false)

  // Filter states
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [roleFilter, setRoleFilter] = useState("all")
  const [activeUserTypeTab, setActiveUserTypeTab] = useState<"family" | "facility_owner">("family")
  const [sortBy, setSortBy] = useState("createdAt")
  const [sortOrder, setSortOrder] = useState("desc")

  // Selection states
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [selectAll, setSelectAll] = useState(false)

  // Pagination
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(10)
  const [totalPages, setTotalPages] = useState(1)

  // Dialog states
  const [showViewDialog, setShowViewDialog] = useState(false)
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showApproveDialog, setShowApproveDialog] = useState(false)
  const [showSuspendDialog, setShowSuspendDialog] = useState(false)
  const [showReactivateDialog, setShowReactivateDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [actionReason, setActionReason] = useState("")

  // Bulk action dialog states
  const [showBulkActivateDialog, setShowBulkActivateDialog] = useState(false)
  const [showBulkSuspendDialog, setShowBulkSuspendDialog] = useState(false)
  const [bulkActionReason, setBulkActionReason] = useState("")

  // Edit form state
  const [editForm, setEditForm] = useState<any>({
    firstName: '',
    lastName: '',
    phone: '',
    status: '',
    role: ''
  })

  // Update state from URL params
  useEffect(() => {
    const tab = searchParams?.get('tab')
    if (tab === 'family' || tab === 'facility_owner') {
      setActiveUserTypeTab(tab as any)
    } else {
      // If no valid tab, ensure we are on family
      setActiveUserTypeTab('family')
    }
  }, [searchParams])

  // Load users
  const loadUsers = async () => {
    try {
      setLoading(true)

      // Determine target role - PRIORITIZE URL parameter to avoid state lag
      const urlTab = searchParams?.get('tab')
      const targetRole = (urlTab === 'family' || urlTab === 'facility_owner') ? urlTab : activeUserTypeTab;

      console.log(`[Admin Users] Loading users for role: ${targetRole} (URL tab: ${urlTab})`)

      const response = await DataAPI.admin.getUsers({
        page: currentPage,
        limit: pageSize,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        role: targetRole,
        search: searchTerm || undefined,
        sortBy,
        sortOrder
      })

      if (response.success && response.data) {
        let fetchedUsers = response.data.users

        // Final strict client-side safety filter to ensure screens never mix
        const currentTargetRole = targetRole.toLowerCase();
        fetchedUsers = fetchedUsers.filter((u: any) => {
          const userRole = (u.role || '').toLowerCase();
          return userRole === currentTargetRole;
        });

        console.log(`[Admin Users] Filtered ${response.data.users.length} down to ${fetchedUsers.length} matching '${currentTargetRole}'`)

        // Fetch full details for each user ensuring phone number availability (God Mode Enrichment)
        try {
          const enrichedUsers = await Promise.all(fetchedUsers.map(async (u: any) => {
            let detailPhone = u.phone || u.phoneNumber || u.mobile;

            // If phone is missing or "N/A", try every possible endpoint
            if (!detailPhone || detailPhone === 'N/A') {
              const endpoints = [
                // 1. Admin Detail (should have everything)
                async () => {
                  const r = await DataAPI.admin.getUserDetails(u._id || u.id);
                  return r.success ? r.data : null;
                },
                // 2. Generic User Detail
                async () => {
                  const r = await DataAPI.users.getUser(u._id || u.id);
                  return r.success ? (r.data?.user || r.data) : null;
                },
                // 3. User Profile endpoint (often has the core profile data)
                async () => {
                  const r = await DataAPI.profile.getProfile(u._id || u.id);
                  return r.success ? (r.data?.profile || r.data) : null;
                },
                // 4. Owner-specific profile (for facility owners)
                async () => {
                  if (u.role !== 'facility_owner') return null;
                  const r = await DataAPI.ownerProfile.getProfile(u._id || u.id);
                  return r.success ? r.data : null;
                }
              ];

              for (const fetcher of endpoints) {
                try {
                  const data = await fetcher();
                  if (!data) continue;

                  const found = data.phone || data.phoneNumber || data.phone_number || data.mobile ||
                    data.profile?.phone || data.profile?.phoneNumber ||
                    data.ownerProfile?.phone || data.ownerProfile?.businessPhone ||
                    data.contact?.phone || data.contactPhone;

                  if (found && found !== 'N/A') {
                    detailPhone = found;
                    break;
                  }
                } catch (e) {
                  // Concurrent failure handle
                }
              }
            }

            return {
              ...u,
              phone: detailPhone || u.phone || 'N/A'
            };
          }))
          setUsers(enrichedUsers)
        } catch (err) {
          console.error("Enrichment failed:", err)
          setUsers(fetchedUsers)
        }

        if (response.data.pagination) {
          setTotalPages(response.data.pagination.totalPages)
        }
      }
    } catch (error: any) {
      toast.error("Failed to load users", {
        title: "Error"
      })
    } finally {
      setLoading(false)
    }
  }

  // Load stats
  const loadStats = async () => {
    try {
      setStatsLoading(true)
      const response = await DataAPI.admin.getUserStats(activeUserTypeTab)

      if (response.success && response.data) {
        setStats(response.data)
      }
    } catch (error) {
      console.error('Failed to load stats:', error)
    } finally {
      setStatsLoading(false)
    }
  }

  // Load on mount and when filters change
  useEffect(() => {
    setUsers([]) // Clear list immediately on tab/filter change to prevent mixed data display
    loadUsers()
  }, [currentPage, pageSize, statusFilter, activeUserTypeTab, sortBy, sortOrder])

  // Load stats on tab change
  useEffect(() => {
    loadStats()
  }, [activeUserTypeTab])

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (currentPage === 1) {
        loadUsers()
      } else {
        setCurrentPage(1)
      }
    }, 500)

    return () => clearTimeout(timer)
  }, [searchTerm])

  // Handle select all
  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedIds([])
      setSelectAll(false)
    } else {
      setSelectedIds(users.map(u => u._id))
      setSelectAll(true)
    }
  }

  // Handle individual selection
  const handleSelect = (id: string) => {
    if (selectedIds.includes(id)) {
      setSelectedIds(selectedIds.filter(i => i !== id))
      setSelectAll(false)
    } else {
      const newSelected = [...selectedIds, id]
      setSelectedIds(newSelected)
      if (newSelected.length === users.length) {
        setSelectAll(true)
      }
    }
  }

  // Load user details
  const loadUserDetails = async (userId: string) => {
    try {
      setIsLoadingUserDetails(true)
      const response = await DataAPI.admin.getUserDetails(userId)

      if (response.success && response.data) {
        setSelectedUser(response.data)
      }
    } catch (error: any) {
      toast.error("Failed to load user details", {
        title: "Error"
      })
    } finally {
      setIsLoadingUserDetails(false)
    }
  }

  // Action handlers
  const handleApprove = async () => {
    if (!selectedUser) return

    setActionLoading(true)
    setShowApproveDialog(false)

    try {
      const response = await DataAPI.admin.updateUserStatus(selectedUser._id || selectedUser.id, 'active')

      if (response.success) {
        toast.success(`${selectedUser.firstName} ${selectedUser.lastName} has been approved and is now active.`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedUser(null)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to approve user", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleSuspend = async () => {
    if (!selectedUser || !actionReason.trim()) {
      toast.error("Please provide a suspension reason", {
        title: "Error"
      })
      return
    }

    setActionLoading(true)
    setShowSuspendDialog(false)

    try {
      const response = await DataAPI.admin.updateUserStatus(selectedUser._id || selectedUser.id, 'suspended', actionReason)

      if (response.success) {
        toast.success(`${selectedUser.firstName} ${selectedUser.lastName} has been suspended.`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedUser(null)
        setActionReason("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to suspend user", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleReactivate = async () => {
    if (!selectedUser) return

    setActionLoading(true)
    setShowReactivateDialog(false)

    try {
      const response = await DataAPI.admin.updateUserStatus(selectedUser._id || selectedUser.id, 'active')

      if (response.success) {
        toast.success(`${selectedUser.firstName} ${selectedUser.lastName} has been reactivated.`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedUser(null)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to reactivate user", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!selectedUser) return

    setActionLoading(true)
    setShowDeleteDialog(false)

    try {
      const response = await DataAPI.admin.deleteUser(selectedUser._id || selectedUser.id)

      if (response.success) {
        toast.success(`${selectedUser.firstName} ${selectedUser.lastName} has been permanently deleted.`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedUser(null)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to delete user", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  // Bulk action handlers
  const handleBulkActivate = async () => {
    if (selectedIds.length === 0) return

    setActionLoading(true)
    setShowBulkActivateDialog(false)

    try {
      const response = await DataAPI.admin.bulkUserAction(selectedIds, 'activate')

      if (response.success) {
        toast.success(`Successfully activated ${selectedIds.length} user${selectedIds.length !== 1 ? 's' : ''}`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedIds([])
        setSelectAll(false)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to activate users", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleBulkSuspend = async () => {
    if (selectedIds.length === 0) return

    if (!bulkActionReason.trim()) {
      toast.error("Please provide a suspension reason", {
        title: "Error"
      })
      return
    }

    setActionLoading(true)
    setShowBulkSuspendDialog(false)

    try {
      const response = await DataAPI.admin.bulkUserAction(selectedIds, 'suspend', bulkActionReason)

      if (response.success) {
        toast.success(`Successfully suspended ${selectedIds.length} user${selectedIds.length !== 1 ? 's' : ''}`, {
          title: "Success!"
        })
        await loadUsers()
        await loadStats()
        setSelectedIds([])
        setSelectAll(false)
        setBulkActionReason("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to suspend users", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleOpenEdit = (user: any) => {
    setSelectedUser(user)
    setEditForm({
      firstName: user.firstName || '',
      lastName: user.lastName || '',
      phone: user.phone || '',
      status: user.status || '',
      role: user.role || ''
    })
    setShowEditDialog(true)
  }

  const handleSaveEdit = async () => {
    if (!selectedUser) return

    setActionLoading(true)

    try {
      const response = await DataAPI.admin.updateUser(selectedUser._id || selectedUser.id, {
        firstName: editForm.firstName,
        lastName: editForm.lastName,
        phone: editForm.phone,
        status: editForm.status,
        role: editForm.role
      })

      if (response.success) {
        toast.success(`${editForm.firstName} ${editForm.lastName} has been updated successfully.`, {
          title: "Success!"
        })
        setShowEditDialog(false)
        await loadUsers()
        setSelectedUser(null)
      } else {
        throw new Error(response.message || 'Failed to update user')
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to update user", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  // Format date
  const formatDate = (date: string) => {
    if (!date) return 'N/A'
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  // Get status badge
  const getStatusBadge = (status: string) => {
    const styles = {
      active: "bg-green-100 text-green-800 border-green-200",
      pending: "bg-yellow-100 text-yellow-800 border-yellow-200",
      suspended: "bg-red-100 text-red-800 border-red-200",
      email_verification: "bg-blue-100 text-blue-800 border-blue-200",
      profile_incomplete: "bg-orange-100 text-orange-800 border-orange-200"
    }

    const icons = {
      active: <CheckCircle className="h-3 w-3 mr-1" />,
      pending: <Clock className="h-3 w-3 mr-1" />,
      suspended: <XCircle className="h-3 w-3 mr-1" />,
      email_verification: <Mail className="h-3 w-3 mr-1" />,
      profile_incomplete: <AlertTriangle className="h-3 w-3 mr-1" />
    }

    return (
      <Badge className={styles[status as keyof typeof styles] || ""}>
        {icons[status as keyof typeof icons]}
        {status.replace('_', ' ').charAt(0).toUpperCase() + status.replace('_', ' ').slice(1)}
      </Badge>
    )
  }

  // Get role badge
  const getRoleBadge = (role: string) => {
    const styles = {
      facility_owner: "bg-purple-100 text-purple-800 border-purple-200",
      family: "bg-blue-100 text-blue-800 border-blue-200",
      family_member: "bg-blue-100 text-blue-800 border-blue-200",
      admin: "bg-indigo-100 text-indigo-800 border-indigo-200",
      super_admin: "bg-pink-100 text-pink-800 border-pink-200"
    }

    return (
      <Badge className={styles[role as keyof typeof styles] || "bg-gray-100 text-gray-800 border-gray-200"}>
        {role.replace('_', ' ').toUpperCase()}
      </Badge>
    )
  }

  // Render loading skeleton
  if (loading && users.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 p-3 md:p-6">
        <div className="space-y-4 md:space-y-6">
          <div className="h-8 w-64 bg-gray-200 animate-pulse rounded" />
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4">
            {[...Array(4)].map((_, i) => (
              <div key={i} className="h-24 bg-gray-200 animate-pulse rounded-lg" />
            ))}
          </div>
          <div className="h-96 bg-gray-200 animate-pulse rounded-lg" />
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30">
      <div className="p-3 md:p-6 lg:p-8 space-y-4 md:space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl md:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              User Management
            </h1>
            <p className="text-sm md:text-base text-gray-600 mt-1 md:mt-2">Manage user accounts, approve facility owners, and monitor user activity</p>
          </div>
          <div className="flex items-center gap-2">
            <Button onClick={() => { loadUsers(); loadStats(); }} variant="outline" size="sm" className="flex-1 sm:flex-none">
              <RefreshCw className={`h-4 w-4 sm:mr-2 ${loading ? 'animate-spin' : ''}`} />
              <span className="hidden sm:inline">Refresh</span>
            </Button>
            <Button variant="outline" size="sm" className="flex-1 sm:flex-none">
              <Download className="h-4 w-4 sm:mr-2" />
              <span className="hidden sm:inline">Export</span>
            </Button>
          </div>
        </div>

        {/* Statistics Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 md:gap-4 mb-6">
          <Card className="bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-600 text-xs md:text-sm font-medium">
                    {activeUserTypeTab === 'family' ? 'Total Family Members' : 'Total Facility Owners'}
                  </p>
                  <p className="text-xl md:text-2xl font-bold text-blue-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> :
                      (activeUserTypeTab === 'family' ? stats.family : stats.facilityOwners)}
                  </p>
                </div>
                <Users className="h-6 w-6 md:h-8 md:w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-50 to-green-100 border-green-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-600 text-xs md:text-sm font-medium">Active</p>
                  <p className="text-xl md:text-2xl font-bold text-green-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> : stats.active}
                  </p>
                </div>
                <CheckCircle className="h-6 w-6 md:h-8 md:w-8 text-green-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-yellow-50 to-yellow-100 border-yellow-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-yellow-600 text-xs md:text-sm font-medium">Pending</p>
                  <p className="text-xl md:text-2xl font-bold text-yellow-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> : stats.pending}
                  </p>
                </div>
                <Clock className="h-6 w-6 md:h-8 md:w-8 text-yellow-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-red-50 to-red-100 border-red-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-red-600 text-xs md:text-sm font-medium">Suspended</p>
                  <p className="text-xl md:text-2xl font-bold text-red-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> : stats.suspended}
                  </p>
                </div>
                <XCircle className="h-6 w-6 md:h-8 md:w-8 text-red-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-teal-50 to-teal-100 border-teal-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-teal-600 text-xs md:text-sm font-medium">Verified</p>
                  <p className="text-xl md:text-2xl font-bold text-teal-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> : stats.verified}
                  </p>
                </div>
                <ShieldCheck className="h-6 w-6 md:h-8 md:w-8 text-teal-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Content with Filters - Tabs Hidden (Managed by Sidebar) */}
        <div className="space-y-4">

          {/* Filters and Search */}
          <Card>
            <CardContent className="p-6">
              <div className="flex flex-col lg:flex-row gap-4">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                  <Input
                    placeholder={`Search ${activeUserTypeTab === 'family' ? 'family members' : 'facility owners'} by name or email...`}
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>

                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger className="w-full lg:w-48">
                    <SelectValue placeholder="All Status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Status</SelectItem>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="suspended">Suspended</SelectItem>
                    <SelectItem value="email_verification">Email Verification</SelectItem>
                    <SelectItem value="profile_incomplete">Profile Incomplete</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-full lg:w-48">
                    <SelectValue placeholder="Sort By" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="createdAt">Newest</SelectItem>
                    <SelectItem value="firstName">Name</SelectItem>
                    <SelectItem value="lastLogin">Last Login</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Bulk Actions Bar */}
          {selectedIds.length > 0 && (
            <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200 shadow-md">
              <CardContent className="p-4">
                <div className="flex items-center justify-between flex-wrap gap-3">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center w-10 h-10 bg-blue-600 text-white rounded-full font-bold">
                      {selectedIds.length}
                    </div>
                    <div>
                      <p className="text-sm font-bold text-blue-900">
                        {selectedIds.length} {selectedIds.length === 1 ? 'user' : 'users'} selected
                      </p>
                      <p className="text-xs text-blue-700">
                        Choose an action to perform
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      size="sm"
                      variant="outline"
                      disabled={actionLoading}
                      onClick={() => setShowBulkActivateDialog(true)}
                      className="bg-white hover:bg-green-50 border-green-300 text-green-700 hover:text-green-800 font-semibold"
                    >
                      {actionLoading ? (
                        <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                      ) : (
                        <CheckCircle className="h-4 w-4 mr-1" />
                      )}
                      Activate
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      disabled={actionLoading}
                      onClick={() => setShowBulkSuspendDialog(true)}
                      className="bg-white hover:bg-orange-50 border-orange-300 text-orange-700 hover:text-orange-800 font-semibold"
                    >
                      {actionLoading ? (
                        <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                      ) : (
                        <XCircle className="h-4 w-4 mr-1" />
                      )}
                      Suspend
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => {
                        setSelectedIds([])
                        setSelectAll(false)
                      }}
                      className="hover:bg-white/60 hover:text-blue-900 font-semibold text-blue-700"
                    >
                      Clear
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Users Table */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>Users ({users.length})</span>
                {loading && <Loader2 className="h-5 w-5 animate-spin text-blue-600" />}
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b-2 border-gray-200">
                    <tr>
                      <th className="px-4 py-3 text-left">
                        <Checkbox
                          checked={selectAll}
                          onCheckedChange={handleSelectAll}
                        />
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        User
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Contact
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Role
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Status
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Joined
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Last Login
                      </th>
                      <th className="px-4 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 bg-white">
                    {loading ? (
                      [...Array(5)].map((_, i) => (
                        <tr key={i}>
                          <td colSpan={8} className="p-4">
                            <div className="h-12 bg-gray-200 animate-pulse rounded" />
                          </td>
                        </tr>
                      ))
                    ) : users.length === 0 ? (
                      <tr>
                        <td colSpan={8} className="p-8 text-center text-gray-500">
                          No users found
                        </td>
                      </tr>
                    ) : (
                      users.map((user) => (
                        <tr key={user._id} className="hover:bg-gray-50 transition-colors">
                          <td className="px-4 py-4">
                            <Checkbox
                              checked={selectedIds.includes(user._id)}
                              onCheckedChange={() => handleSelect(user._id)}
                            />
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-3 min-w-0">
                              <div className="flex-shrink-0">
                                <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-semibold">
                                  {user.firstName?.[0]}{user.lastName?.[0]}
                                </div>
                              </div>
                              <div className="min-w-0 flex-1">
                                <p className="font-semibold text-gray-900 text-sm truncate">
                                  {user.firstName} {user.lastName}
                                </p>
                                <div className="flex items-center gap-2 mt-1">
                                  {user.emailVerified && (
                                    <Badge className="bg-green-100 text-green-700 text-xs border-green-200">
                                      <ShieldCheck className="h-3 w-3 mr-1" />
                                      Verified
                                    </Badge>
                                  )}
                                </div>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <div className="text-sm">
                              <p className="text-gray-900 flex items-center gap-1">
                                <Mail className="h-3 w-3 text-gray-400" />
                                {user.email}
                              </p>
                              <p className="text-gray-500 text-xs mt-1 flex items-center gap-1">
                                <Phone className="h-3 w-3" />
                                {[user.phone, user.phoneNumber, user.mobile, user.profile?.phone, user.contact?.phone].find(p => p && p !== 'N/A') || 'N/A'}
                              </p>
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            {getRoleBadge(user.role)}
                          </td>
                          <td className="px-4 py-4">
                            {getStatusBadge(user.status)}
                          </td>
                          <td className="px-4 py-4">
                            <div className="text-sm">
                              <p className="text-gray-900 flex items-center gap-1">
                                <Calendar className="h-3 w-3 text-gray-400" />
                                {formatDate(user.createdAt)}
                              </p>
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <div className="text-sm text-gray-600">
                              {user.lastLogin ? formatDate(user.lastLogin) : 'Never'}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex items-center justify-end gap-2">
                              {/* View button hidden for now */}
                              {/* <Button 
                              size="sm" 
                              variant="outline"
                              onClick={() => {
                                loadUserDetails(user._id)
                                setShowViewDialog(true)
                              }}
                            >
                              <Eye className="h-4 w-4 mr-1" />
                              View
                            </Button> */}
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button size="sm" variant="ghost" className="h-8 w-8 p-0">
                                    <span className="sr-only">Open menu</span>
                                    <MoreVertical className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end" className="w-48 z-50">
                                  <DropdownMenuLabel>Actions</DropdownMenuLabel>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={() => handleOpenEdit(user)}
                                  >
                                    <Edit className="h-4 w-4 mr-2 text-blue-600" />
                                    Edit User
                                  </DropdownMenuItem>
                                  <DropdownMenuSeparator />
                                  {(user.status === 'pending' || user.status === 'email_verification' || user.status === 'profile_incomplete') && (
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedUser(user)
                                        setShowApproveDialog(true)
                                      }}
                                    >
                                      <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                      Approve
                                    </DropdownMenuItem>
                                  )}
                                  {user.status === 'active' && (
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedUser(user)
                                        setShowSuspendDialog(true)
                                      }}
                                    >
                                      <XCircle className="h-4 w-4 mr-2 text-orange-600" />
                                      Suspend
                                    </DropdownMenuItem>
                                  )}
                                  {user.status === 'suspended' && (
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedUser(user)
                                        setShowReactivateDialog(true)
                                      }}
                                    >
                                      <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                      Reactivate
                                    </DropdownMenuItem>
                                  )}
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedUser(user)
                                      setShowDeleteDialog(true)
                                    }}
                                    className="text-red-600"
                                  >
                                    <Trash2 className="h-4 w-4 mr-2" />
                                    Delete
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>

          {/* Pagination */}
          <div className="flex items-center justify-between">
            <p className="text-sm text-gray-700">
              Page {currentPage} of {totalPages} • {users.length} users shown
            </p>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                disabled={currentPage === 1 || loading}
                onClick={() => setCurrentPage(p => p - 1)}
              >
                Previous
              </Button>
              {[...Array(Math.min(totalPages, 5))].map((_, i) => {
                const pageNum = i + 1
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="sm"
                    onClick={() => setCurrentPage(pageNum)}
                    disabled={loading}
                  >
                    {pageNum}
                  </Button>
                )
              })}
              <Button
                variant="outline"
                size="sm"
                disabled={currentPage === totalPages || loading}
                onClick={() => setCurrentPage(p => p + 1)}
              >
                Next
              </Button>
            </div>
          </div>

        </div>

        {/* View User Dialog */}
        <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
          <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center justify-between">
                <span>{selectedUser ? `${selectedUser.firstName} ${selectedUser.lastName}` : 'User Details'}</span>
                {selectedUser && (
                  <div className="flex items-center gap-2">
                    {getRoleBadge(selectedUser.role)}
                    {getStatusBadge(selectedUser.status)}
                  </div>
                )}
              </DialogTitle>
              <DialogDescription>
                Complete user details and information
              </DialogDescription>
            </DialogHeader>

            {isLoadingUserDetails ? (
              <div className="space-y-6 py-4">
                <div className="grid grid-cols-2 gap-4">
                  <Skeleton className="h-32" />
                  <Skeleton className="h-32" />
                </div>
                <Skeleton className="h-24" />
              </div>
            ) : selectedUser ? (
              <div className="space-y-6 py-4">
                {/* Basic Info */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Email</Label>
                    <p className="text-sm mt-1">{selectedUser.email}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Phone</Label>
                    <p className="text-sm mt-1">{selectedUser.phone || 'Not provided'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Member Since</Label>
                    <p className="text-sm mt-1">{formatDate(selectedUser.createdAt)}</p>
                  </div>
                  {selectedUser.lastLogin && (
                    <div>
                      <Label className="text-xs text-gray-500">Last Login</Label>
                      <p className="text-sm mt-1">{formatDate(selectedUser.lastLogin)}</p>
                    </div>
                  )}
                  <div>
                    <Label className="text-xs text-gray-500">Email Verified</Label>
                    <p className="text-sm mt-1">{selectedUser.emailVerified ? 'Yes' : 'No'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Profile Status</Label>
                    <p className="text-sm mt-1">{selectedUser.profile?.profileCompleted ? 'Complete' : 'Incomplete'}</p>
                  </div>
                </div>

                {/* Personal Details */}
                {(selectedUser.profile?.gender || selectedUser.profile?.dateOfBirth || selectedUser.profile?.bio) && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-3 text-sm">Personal Details</h4>
                    <div className="grid grid-cols-2 gap-4">
                      {selectedUser.profile?.gender && (
                        <div>
                          <Label className="text-xs text-gray-500">Gender</Label>
                          <p className="text-sm mt-1 capitalize">{selectedUser.profile.gender.replace('_', ' ')}</p>
                        </div>
                      )}
                      {selectedUser.profile?.dateOfBirth && (
                        <div>
                          <Label className="text-xs text-gray-500">Date of Birth</Label>
                          <p className="text-sm mt-1">{formatDate(selectedUser.profile.dateOfBirth)}</p>
                        </div>
                      )}
                      {selectedUser.profile?.bio && (
                        <div className="col-span-2">
                          <Label className="text-xs text-gray-500">Bio</Label>
                          <p className="text-sm mt-1 text-gray-700">{selectedUser.profile.bio}</p>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Account Security */}
                <div className="border-t pt-4">
                  <h4 className="font-semibold mb-3 text-sm">Account Security</h4>
                  <div className="grid grid-cols-2 gap-4">
                    {selectedUser.loginAttempts > 0 && (
                      <div>
                        <Label className="text-xs text-red-600">Failed Login Attempts</Label>
                        <p className="text-sm mt-1 text-red-700 font-semibold">{selectedUser.loginAttempts}</p>
                      </div>
                    )}
                    {selectedUser.lockUntil && (
                      <div>
                        <Label className="text-xs text-red-600">Account Locked Until</Label>
                        <p className="text-sm mt-1 text-red-700">{new Date(selectedUser.lockUntil).toLocaleString()}</p>
                      </div>
                    )}
                    <div>
                      <Label className="text-xs text-gray-500">Account Created</Label>
                      <p className="text-sm mt-1">{formatDate(selectedUser.createdAt)}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-gray-500">Last Updated</Label>
                      <p className="text-sm mt-1">{formatDate(selectedUser.updatedAt)}</p>
                    </div>
                  </div>
                </div>

                {/* Care Preferences for Family Users */}
                {selectedUser.profile?.carePreferences && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-3 text-sm">Care Preferences</h4>
                    <div className="grid grid-cols-2 gap-4">
                      {selectedUser.profile.carePreferences.careTypes && selectedUser.profile.carePreferences.careTypes.length > 0 && (
                        <div className="col-span-2">
                          <Label className="text-xs text-gray-500">Care Types</Label>
                          <div className="flex flex-wrap gap-2 mt-1">
                            {selectedUser.profile.carePreferences.careTypes.map((type: string, index: number) => (
                              <Badge key={index} variant="outline">
                                {type.replace('_', ' ')}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      )}
                      {selectedUser.profile.carePreferences.budgetRange && (
                        <div>
                          <Label className="text-xs text-gray-500">Budget Range</Label>
                          <p className="text-sm mt-1">{selectedUser.profile.carePreferences.budgetRange}</p>
                        </div>
                      )}
                      {selectedUser.profile.carePreferences.preferredLocation && (
                        <div>
                          <Label className="text-xs text-gray-500">Preferred Location</Label>
                          <p className="text-sm mt-1">{selectedUser.profile.carePreferences.preferredLocation}</p>
                        </div>
                      )}
                      {selectedUser.profile.carePreferences.moveInTimeframe && (
                        <div>
                          <Label className="text-xs text-gray-500">Move-in Timeframe</Label>
                          <p className="text-sm mt-1">{selectedUser.profile.carePreferences.moveInTimeframe}</p>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Business Information for Facility Owners */}
                {selectedUser.ownerProfile && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-3 text-sm">Business Information</h4>
                    <div className="grid grid-cols-2 gap-4">
                      {selectedUser.ownerProfile.businessName && (
                        <div>
                          <Label className="text-xs text-gray-500">Business Name</Label>
                          <p className="text-sm mt-1">{selectedUser.ownerProfile.businessName}</p>
                        </div>
                      )}
                      {selectedUser.ownerProfile.businessType && (
                        <div>
                          <Label className="text-xs text-gray-500">Business Type</Label>
                          <p className="text-sm mt-1">{selectedUser.ownerProfile.businessType}</p>
                        </div>
                      )}
                      {selectedUser.ownerProfile.licenseNumber && (
                        <div>
                          <Label className="text-xs text-gray-500">License Number</Label>
                          <p className="text-sm mt-1">{selectedUser.ownerProfile.licenseNumber}</p>
                        </div>
                      )}
                      {selectedUser.ownerProfile.verification && (
                        <div>
                          <Label className="text-xs text-gray-500">Verification Status</Label>
                          <Badge variant={selectedUser.ownerProfile.verification.status === 'verified' ? 'default' : 'secondary'} className="mt-1">
                            {selectedUser.ownerProfile.verification.status || 'Unverified'}
                          </Badge>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Facilities Section for Facility Owners */}
                {selectedUser.facilities && selectedUser.facilities.length > 0 && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-3 text-sm flex items-center justify-between">
                      <span>Owned Facilities ({selectedUser.stats?.facilitiesOwned || 0})</span>
                      <div className="flex items-center gap-3 text-xs">
                        <span className="text-green-600 font-medium">Active: {selectedUser.stats?.activeFacilities || 0}</span>
                        <span className="text-yellow-600 font-medium">Pending: {selectedUser.stats?.pendingFacilities || 0}</span>
                      </div>
                    </h4>
                    <div className="grid grid-cols-1 gap-3">
                      {selectedUser.facilities.map((facility: any) => (
                        <div key={facility.id} className="border rounded-lg p-3">
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <p className="font-medium text-sm text-gray-900">{facility.name}</p>
                              <p className="text-xs text-gray-600 mt-1 flex items-center">
                                <MapPin className="h-3 w-3 mr-1" />
                                {typeof facility.location === 'string'
                                  ? facility.location
                                  : `${facility.location?.city || ''}, ${facility.location?.state || ''}`}
                              </p>
                              <p className="text-xs text-gray-500 mt-1">
                                Created: {formatDate(facility.createdAt)}
                              </p>
                            </div>
                            <Badge variant={
                              facility.status === 'active' ? 'default' :
                                facility.status === 'pending' ? 'secondary' :
                                  'outline'
                            } className="text-xs">
                              {facility.status}
                            </Badge>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Mailing Address */}
                {selectedUser.profile?.mailingAddress && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-3 text-sm">Mailing Address</h4>
                    <div className="border rounded-lg p-3">
                      <div className="space-y-1 text-sm">
                        {selectedUser.profile.mailingAddress.street && (
                          <p className="text-gray-900">{selectedUser.profile.mailingAddress.street}</p>
                        )}
                        {(selectedUser.profile.mailingAddress.city || selectedUser.profile.mailingAddress.state || selectedUser.profile.mailingAddress.zipCode) && (
                          <p className="text-gray-900">
                            {[
                              selectedUser.profile.mailingAddress.city,
                              selectedUser.profile.mailingAddress.state,
                              selectedUser.profile.mailingAddress.zipCode
                            ].filter(Boolean).join(', ')}
                          </p>
                        )}
                        {selectedUser.profile.mailingAddress.country && (
                          <p className="text-gray-600">{selectedUser.profile.mailingAddress.country}</p>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="text-center py-12">
                <User className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                <p className="text-gray-500">No user data available</p>
              </div>
            )}

            <DialogFooter>
              <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                Close
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Edit Dialog */}
        <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Edit User: {selectedUser?.firstName} {selectedUser?.lastName}</DialogTitle>
              <DialogDescription>
                Update user information. Changes will be saved immediately.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-6 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="edit-firstName">First Name *</Label>
                  <Input
                    id="edit-firstName"
                    value={editForm.firstName}
                    onChange={(e) => setEditForm({ ...editForm, firstName: e.target.value })}
                    placeholder="First name"
                  />
                </div>
                <div>
                  <Label htmlFor="edit-lastName">Last Name *</Label>
                  <Input
                    id="edit-lastName"
                    value={editForm.lastName}
                    onChange={(e) => setEditForm({ ...editForm, lastName: e.target.value })}
                    placeholder="Last name"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="edit-phone">Phone</Label>
                <Input
                  id="edit-phone"
                  value={editForm.phone}
                  onChange={(e) => setEditForm({ ...editForm, phone: e.target.value })}
                  placeholder="(555) 123-4567"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="edit-status">Status</Label>
                  <Select value={editForm.status} onValueChange={(value) => setEditForm({ ...editForm, status: value })}>
                    <SelectTrigger id="edit-status">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="suspended">Suspended</SelectItem>
                      <SelectItem value="email_verification">Email Verification</SelectItem>
                      <SelectItem value="profile_incomplete">Profile Incomplete</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="edit-role">Role</Label>
                  <Select value={editForm.role} onValueChange={(value) => setEditForm({ ...editForm, role: value })}>
                    <SelectTrigger id="edit-role">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="family">Family Member</SelectItem>
                      <SelectItem value="facility_owner">Facility Owner</SelectItem>
                      <SelectItem value="admin">Admin</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setShowEditDialog(false)} disabled={actionLoading}>
                Cancel
              </Button>
              <Button onClick={handleSaveEdit} disabled={actionLoading}>
                {actionLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin mr-2" />
                    Saving...
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4 mr-2" />
                    Save Changes
                  </>
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Approve Dialog */}
        <AlertDialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Approve User?</AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to approve <strong>{selectedUser?.firstName} {selectedUser?.lastName}</strong>?
                The user will be notified via email and their account will become active.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={actionLoading}>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={handleApprove} disabled={actionLoading}>
                {actionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <CheckCircle className="h-4 w-4 mr-2" />}
                Approve
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Suspend Dialog */}
        <Dialog open={showSuspendDialog} onOpenChange={setShowSuspendDialog}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Suspend User</DialogTitle>
              <DialogDescription>
                Please provide a reason for suspending <strong>{selectedUser?.firstName} {selectedUser?.lastName}</strong>.
                The user will be removed from active listings.
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <Label htmlFor="suspend-reason">Suspension Reason *</Label>
              <Textarea
                id="suspend-reason"
                value={actionReason}
                onChange={(e) => setActionReason(e.target.value)}
                placeholder="Please explain why this user is being suspended..."
                rows={4}
                className="mt-2"
              />
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => {
                setShowSuspendDialog(false)
                setActionReason("")
              }} disabled={actionLoading}>
                Cancel
              </Button>
              <Button variant="destructive" onClick={handleSuspend} disabled={actionLoading || !actionReason.trim()}>
                {actionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <XCircle className="h-4 w-4 mr-2" />}
                Suspend
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Reactivate Dialog */}
        <AlertDialog open={showReactivateDialog} onOpenChange={setShowReactivateDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Reactivate User?</AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to reactivate <strong>{selectedUser?.firstName} {selectedUser?.lastName}</strong>?
                The user will regain full access to their account.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={actionLoading}>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={handleReactivate} disabled={actionLoading}>
                {actionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <CheckCircle className="h-4 w-4 mr-2" />}
                Reactivate
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Delete Dialog */}
        <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Delete User Permanently?</AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to permanently delete <strong>{selectedUser?.firstName} {selectedUser?.lastName}</strong>?
                This action cannot be undone. All associated data including reviews and favorites will be removed.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={actionLoading}>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={handleDelete} disabled={actionLoading} className="bg-red-600 hover:bg-red-700">
                {actionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                Delete Permanently
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Bulk Activate Dialog */}
        <AlertDialog open={showBulkActivateDialog} onOpenChange={setShowBulkActivateDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle className="flex items-center gap-2">
                <CheckCircle className="h-5 w-5 text-green-600" />
                Activate Selected Users?
              </AlertDialogTitle>
              <AlertDialogDescription>
                You are about to activate <strong>{selectedIds.length} user{selectedIds.length !== 1 ? 's' : ''}</strong>.
                {selectedIds.length > 1 && ' All selected users'} will regain full access to their account{selectedIds.length !== 1 ? 's' : ''}.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={actionLoading}>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleBulkActivate}
                disabled={actionLoading}
                className="bg-green-600 hover:bg-green-700"
              >
                {actionLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin mr-2" />
                    Activating...
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4 mr-2" />
                    Activate {selectedIds.length} User{selectedIds.length !== 1 ? 's' : ''}
                  </>
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Bulk Suspend Dialog */}
        <AlertDialog open={showBulkSuspendDialog} onOpenChange={setShowBulkSuspendDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle className="flex items-center gap-2">
                <AlertTriangle className="h-5 w-5 text-orange-600" />
                Suspend Selected Users?
              </AlertDialogTitle>
              <AlertDialogDescription>
                You are about to suspend <strong>{selectedIds.length} user{selectedIds.length !== 1 ? 's' : ''}</strong>.
                {selectedIds.length > 1 && ' All selected users'} will lose access to their account{selectedIds.length !== 1 ? 's' : ''} and all active sessions will be invalidated.
              </AlertDialogDescription>
            </AlertDialogHeader>

            <div className="py-4">
              <Label htmlFor="bulk-suspend-reason" className="text-sm font-semibold">
                Suspension Reason <span className="text-red-500">*</span>
              </Label>
              <Textarea
                id="bulk-suspend-reason"
                value={bulkActionReason}
                onChange={(e) => setBulkActionReason(e.target.value)}
                placeholder="Please provide a detailed reason for suspending these users..."
                className="mt-2 min-h-[100px]"
                disabled={actionLoading}
              />
              <p className="text-xs text-gray-500 mt-2">
                This reason will be recorded in the system logs and may be visible to the users.
              </p>
            </div>

            <AlertDialogFooter>
              <AlertDialogCancel
                disabled={actionLoading}
                onClick={() => setBulkActionReason("")}
              >
                Cancel
              </AlertDialogCancel>
              <AlertDialogAction
                onClick={handleBulkSuspend}
                disabled={actionLoading || !bulkActionReason.trim()}
                className="bg-orange-600 hover:bg-orange-700"
              >
                {actionLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin mr-2" />
                    Suspending...
                  </>
                ) : (
                  <>
                    <XCircle className="h-4 w-4 mr-2" />
                    Suspend {selectedIds.length} User{selectedIds.length !== 1 ? 's' : ''}
                  </>
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  )
}
