"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
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 { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
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,
  ExternalLink
} from "lucide-react"

export default function AdminFacilitiesPage() {
  const toast = useToast()

  // Data states
  const [facilities, setFacilities] = useState<any[]>([])
  interface FacilityStats {
    total: number;
    active: number;
    pending: number;
    suspended: number;
    rejected: number;
    closed: number;
    verified: number;
    averageRating: number;
    categories?: Record<string, number>;
  }

  const [stats, setStats] = useState<FacilityStats>({
    total: 0,
    active: 0,
    pending: 0,
    suspended: 0,
    rejected: 0,
    closed: 0,
    verified: 0,
    averageRating: 0,
    categories: {}
  })
  const [selectedFacility, setSelectedFacility] = useState<any | null>(null)

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

  // Filter states
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [categoryFilter, setCategoryFilter] = useState("all")
  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 [showRejectDialog, setShowRejectDialog] = useState(false)
  const [showSuspendDialog, setShowSuspendDialog] = useState(false)
  const [showCloseDialog, setShowCloseDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showFeaturedDialog, setShowFeaturedDialog] = useState(false)
  const [actionReason, setActionReason] = useState("")
  const [featuredUntilDate, setFeaturedUntilDate] = useState("")

  // Edit form state
  const [editForm, setEditForm] = useState<any>({
    name: '',
    description: '',
    phone: '',
    email: '',
    website: '',
    address: '',
    city: '',
    state: '',
    zipCode: '',
    licenseNumber: '',
    totalCapacity: '',
    careTypes: []
  })

  // Load facilities
  const loadFacilities = async () => {
    try {
      setLoading(true)

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

      if (response.success && response.data) {
        let fetchedFacilities = response.data.facilities

        try {
          const enrichedFacilities = await Promise.all(fetchedFacilities.map(async (f: any) => {
            // If contact info is missing, try to fetch details
            if ((!f.contact?.phone && !f.phone) || (!f.contact?.email && !f.email)) {
              try {
                // Try public endpoint or admin endpoint if available (using public here as fallback)
                const detailRes = await DataAPI.facilities.getFacility(f._id || f.id)
                if (detailRes.success && detailRes.data) {
                  return { ...f, ...detailRes.data }
                }
              } catch (e) { }
            }
            return f
          }))
          setFacilities(enrichedFacilities)
        } catch (err) {
          setFacilities(fetchedFacilities)
        }

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

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

      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(() => {
    loadFacilities()
  }, [currentPage, pageSize, statusFilter, categoryFilter, sortBy, sortOrder])

  // Load stats on mount
  useEffect(() => {
    loadStats()
  }, [])

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

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

  // Handle select all
  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedIds([])
      setSelectAll(false)
    } else {
      setSelectedIds(facilities.map(f => f._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 === facilities.length) {
        setSelectAll(true)
      }
    }
  }

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

    setActionLoading(true)
    setShowApproveDialog(false)

    try {
      const response = await DataAPI.admin.updateFacilityStatus(selectedFacility._id, 'active')

      if (response.success) {
        toast.success(`${selectedFacility.name} has been approved and is now active.`, {
          title: "Success!"
        })
        await loadFacilities()
        await loadStats()
        setSelectedFacility(null)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to approve facility", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

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

    setActionLoading(true)
    setShowRejectDialog(false)

    try {
      const response = await DataAPI.admin.updateFacilityStatus(selectedFacility._id, 'rejected', actionReason)

      if (response.success) {
        toast.success(`${selectedFacility.name} has been rejected.`, {
          title: "Success!"
        })
        await loadFacilities()
        await loadStats()
        setSelectedFacility(null)
        setActionReason("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to reject facility", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

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

    setActionLoading(true)
    setShowSuspendDialog(false)

    try {
      const response = await DataAPI.admin.updateFacilityStatus(selectedFacility._id, 'suspended', actionReason)

      if (response.success) {
        toast.success(`${selectedFacility.name} has been suspended.`, {
          title: "Success!"
        })
        await loadFacilities()
        await loadStats()
        setSelectedFacility(null)
        setActionReason("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to suspend facility", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

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

    setActionLoading(true)
    setShowDeleteDialog(false)

    try {
      // Get auth token from localStorage
      const token = localStorage.getItem('geezer_guide_token')

      // Note: Using the delete endpoint from the API
      const response = await fetch(`/api/admin/facilities/${selectedFacility._id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        }
      })

      const data = await response.json()

      if (data.success) {
        toast.success(`${selectedFacility.name} has been permanently deleted.`, {
          title: "Success!"
        })
        await loadFacilities()
        await loadStats()
        setSelectedFacility(null)
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to delete facility", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

  const handleOpenEdit = (facility: any) => {
    setSelectedFacility(facility)
    setEditForm({
      name: facility.name || '',
      description: facility.description || '',
      phone: facility.contact?.phone || '',
      email: facility.contact?.email || '',
      website: facility.contact?.website || '',
      address: facility.location?.address || '',
      city: facility.location?.city || '',
      state: facility.location?.state || '',
      zipCode: facility.location?.zipCode || '',
      licenseNumber: facility.licensing?.licenseNumber || '',
      totalCapacity: facility.capacity?.totalLicensed || '',
      careTypes: facility.careTypes || []
    })
    setShowEditDialog(true)
  }

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

    setActionLoading(true)

    try {
      const token = localStorage.getItem('geezer_guide_token')

      const response = await fetch(`/api/admin/facilities/${selectedFacility._id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          name: editForm.name,
          description: editForm.description,
          contact: {
            phone: editForm.phone,
            email: editForm.email,
            website: editForm.website
          },
          location: {
            address: editForm.address,
            city: editForm.city,
            state: editForm.state,
            zipCode: editForm.zipCode
          },
          licensing: {
            licenseNumber: editForm.licenseNumber
          },
          capacity: {
            totalLicensed: parseInt(editForm.totalCapacity) || 0
          },
          careTypes: editForm.careTypes
        })
      })

      const data = await response.json()

      if (data.success) {
        toast.success(`${editForm.name} has been updated successfully.`, {
          title: "Success!"
        })
        setShowEditDialog(false)
        await loadFacilities()
        setSelectedFacility(null)
      } else {
        throw new Error(data.message || 'Failed to update facility')
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to update facility", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

  const handleVerifyToggle = async (facility: any) => {
    setActionLoading(true)

    try {
      const response = await DataAPI.admin.verifyFacility(facility._id, !facility.verified)

      if (response.success) {
        toast.success(`${facility.name} ${facility.verified ? 'unverified' : 'verified'} successfully.`, {
          title: "Success!"
        })
        await loadFacilities()
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to update verification status", { title: "Error" })
    } finally {
      setActionLoading(false)
    }
  }

  const handleClose = async () => {
    if (!selectedFacility || !actionReason.trim()) {
      toast.error("Please provide a reason for closing this facility", {
        title: "Error"
      })
      return
    }

    setActionLoading(true)
    setShowCloseDialog(false)

    try {
      const response = await DataAPI.admin.updateFacilityStatus(selectedFacility._id, 'closed', actionReason)

      if (response.success) {
        toast.success(`${selectedFacility.name} has been marked as closed.`, {
          title: "Success!"
        })
        await loadFacilities()
        await loadStats()
        setSelectedFacility(null)
        setActionReason("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to close facility", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  const handleToggleFeatured = async () => {
    if (!selectedFacility) return

    setActionLoading(true)
    setShowFeaturedDialog(false)

    try {
      const token = localStorage.getItem('geezer_guide_token')

      const updateData: any = {
        featured: !selectedFacility.featured
      }

      // If featuring, set the expiry date
      if (!selectedFacility.featured && featuredUntilDate) {
        updateData.featuredUntil = new Date(featuredUntilDate)
      }

      const response = await fetch(`/api/admin/facilities/${selectedFacility._id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(updateData)
      })

      const data = await response.json()

      if (data.success) {
        toast.success(`${selectedFacility.name} ${selectedFacility.featured ? 'removed from' : 'added to'} featured listings.`, {
          title: "Success!"
        })
        await loadFacilities()
        setSelectedFacility(null)
        setFeaturedUntilDate("")
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to update featured status", {
        title: "Error"
      })
    } finally {
      setActionLoading(false)
    }
  }

  // Bulk actions
  const handleBulkAction = async (action: string) => {
    if (selectedIds.length === 0) {
      toast.error("Please select facilities to perform bulk action", { title: "No Selection" })
      return
    }

    setActionLoading(true)

    try {
      const response = await DataAPI.admin.bulkAction(action, selectedIds)

      if (response.success) {
        toast.success(`Bulk ${action} completed for ${selectedIds.length} facilities.`, {
          title: "Success!"
        })
        setSelectedIds([])
        setSelectAll(false)
        await loadFacilities()
        await loadStats()
      }
    } catch (error: any) {
      toast.error(error.message || `Failed to perform bulk ${action}`, { 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 color
  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-orange-100 text-orange-800 border-orange-200",
      rejected: "bg-red-100 text-red-800 border-red-200",
      closed: "bg-gray-100 text-gray-800 border-gray-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" />,
      rejected: <XSquare className="h-3 w-3 mr-1" />,
      closed: <Building className="h-3 w-3 mr-1" />
    }

    return (
      <Badge className={`${styles[status as keyof typeof styles] || ""} flex items-center whitespace-nowrap`}>
        {icons[status as keyof typeof icons]}
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </Badge>
    )
  }

  // Render loading skeleton
  if (loading && facilities.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 p-6">
        <div className="space-y-6">
          <div className="h-8 w-64 bg-gray-200 animate-pulse rounded" />
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 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">
              Facility Management
            </h1>
            <p className="text-sm md:text-base text-gray-600 mt-1 md:mt-2">Manage and monitor all senior care facilities</p>
          </div>
          <div className="flex items-center gap-2">
            <Button onClick={() => { loadFacilities(); 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>

        {/* Main Statistics Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4">
          <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">Total Facilities</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" /> : stats.total}
                  </p>
                </div>
                <Building 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 Review</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-cyan-50 to-cyan-100 border-cyan-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-cyan-600 text-xs md:text-sm font-medium">Verified</p>
                  <p className="text-xl md:text-2xl font-bold text-cyan-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-cyan-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Secondary Status Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4">
          <Card className="bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-orange-600 text-xs md:text-sm font-medium">Suspended</p>
                  <p className="text-xl md:text-2xl font-bold text-orange-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-orange-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">Rejected</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.rejected}
                  </p>
                </div>
                <XSquare className="h-6 w-6 md:h-8 md:w-8 text-red-600" />
              </div>
            </CardContent>
          </Card>

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

          <Card className="bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
            <CardContent className="p-4 md:p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-purple-600 text-xs md:text-sm font-medium">Avg Rating</p>
                  <p className="text-xl md:text-2xl font-bold text-purple-900">
                    {statsLoading ? <Loader2 className="h-5 w-5 md:h-6 md:w-6 animate-spin" /> : stats.averageRating.toFixed(1)}
                  </p>
                </div>
                <Star className="h-6 w-6 md:h-8 md:w-8 text-purple-600 fill-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Category KPI Cards */}
        <div>
          <h2 className="text-lg md:text-xl font-semibold text-gray-900 mb-3 md:mb-4">Facilities by Category</h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-2 md:gap-3">
            {[
              { name: 'Skilled Nursing', bg: 'from-indigo-50 to-indigo-100', border: 'border-indigo-200', text: 'text-indigo-600', textDark: 'text-indigo-900' },
              { name: 'Assisted Living', bg: 'from-teal-50 to-teal-100', border: 'border-teal-200', text: 'text-teal-600', textDark: 'text-teal-900' },
              { name: 'Memory Care', bg: 'from-pink-50 to-pink-100', border: 'border-pink-200', text: 'text-pink-600', textDark: 'text-pink-900' },
              { name: 'Boarding Home', bg: 'from-orange-50 to-orange-100', border: 'border-orange-200', text: 'text-orange-600', textDark: 'text-orange-900' }
            ].map((category) => {
              const count = stats.categories?.[category.name] || 0
              const isSelected = categoryFilter === category.name
              return (
                <Card
                  key={category.name}
                  className={`bg-gradient-to-br ${category.bg} ${category.border} cursor-pointer hover:shadow-md transition-shadow ${isSelected ? 'ring-2 ring-blue-500' : ''}`}
                  onClick={() => {
                    setCategoryFilter(isSelected ? 'all' : category.name)
                    setCurrentPage(1)
                  }}
                >
                  <CardContent className="p-3 md:p-4">
                    <div className="flex items-center justify-between">
                      <div className="flex-1 min-w-0">
                        <p className={`text-[10px] md:text-xs font-medium ${category.text} truncate`}>
                          {category.name}
                        </p>
                        <p className={`text-lg md:text-xl font-bold ${category.textDark} mt-1`}>
                          {statsLoading ? <Loader2 className="h-4 w-4 md:h-5 md:w-5 animate-spin" /> : count}
                        </p>
                      </div>
                      {isSelected && (
                        <div className="ml-2">
                          <CheckCircle className="h-4 w-4 md:h-5 md:w-5 text-green-600" />
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )
            })}
          </div>
        </div>

        {/* Filters and Search */}
        <Card>
          <CardContent className="p-4 md:p-6">
            <div className="flex flex-col gap-3 md: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 facilities by name or location..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>

              <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger className="w-full">
                    <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="rejected">❌ Rejected</SelectItem>
                    <SelectItem value="closed">🏚️ Closed</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={categoryFilter} onValueChange={(value) => { setCategoryFilter(value); setCurrentPage(1); }}>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="All Categories" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Categories</SelectItem>
                    <SelectItem value="Skilled Nursing">Skilled Nursing</SelectItem>
                    <SelectItem value="Assisted Living">Assisted Living</SelectItem>
                    <SelectItem value="Memory Care">Memory Care</SelectItem>
                    <SelectItem value="Boarding Home">Boarding Home</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-full col-span-2 lg:col-span-1">
                    <SelectValue placeholder="Sort By" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="createdAt">Newest</SelectItem>
                    <SelectItem value="name">Name</SelectItem>
                    <SelectItem value="rating">Rating</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Bulk Actions Bar */}
        {selectedIds.length > 0 && (
          <Card className="bg-blue-50 border-blue-200">
            <CardContent className="p-3 md:p-4">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <p className="text-xs md:text-sm font-medium text-blue-900">
                  {selectedIds.length} {selectedIds.length === 1 ? 'facility' : 'facilities'} selected
                </p>
                <div className="flex items-center gap-2">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleBulkAction('approve')}
                    disabled={actionLoading}
                    className="flex-1 sm:flex-none"
                  >
                    <CheckCircle className="h-3 w-3 md:h-4 md:w-4 md:mr-1" />
                    <span className="hidden sm:inline">Approve</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleBulkAction('suspend')}
                    disabled={actionLoading}
                    className="flex-1 sm:flex-none"
                  >
                    <XCircle className="h-3 w-3 md:h-4 md:w-4 md:mr-1" />
                    <span className="hidden sm:inline">Suspend</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => {
                      setSelectedIds([])
                      setSelectAll(false)
                    }}
                    className="flex-1 sm:flex-none"
                  >
                    Clear
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Facilities Table */}
        <Card>
          <CardHeader className="px-4 md:px-6">
            <CardTitle className="flex items-center justify-between text-base md:text-lg">
              <span>Facilities ({facilities.length})</span>
              {loading && <Loader2 className="h-4 w-4 md:h-5 md:w-5 animate-spin text-blue-600" />}
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto -mx-4 md:mx-0">
              <table className="w-full min-w-[800px]">
                <thead className="bg-gray-50 border-b-2 border-gray-200">
                  <tr>
                    <th className="px-2 md:px-4 py-3 text-left">
                      <Checkbox
                        checked={selectAll}
                        onCheckedChange={handleSelectAll}
                      />
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Facility
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Owner
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Contact
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Location
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Featured
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Submitted
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Status
                    </th>
                    <th className="px-2 md:px-4 py-3 text-left text-[10px] md:text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      Rating
                    </th>
                    <th className="px-2 md:px-4 py-3 text-right text-[10px] md: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={10} className="p-4">
                          <div className="h-12 bg-gray-200 animate-pulse rounded" />
                        </td>
                      </tr>
                    ))
                  ) : facilities.length === 0 ? (
                    <tr>
                      <td colSpan={10} className="p-8 text-center text-gray-500">
                        No facilities found
                      </td>
                    </tr>
                  ) : (
                    facilities.map((facility) => (
                      <tr key={facility._id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-4 py-4">
                          <Checkbox
                            checked={selectedIds.includes(facility._id)}
                            onCheckedChange={() => handleSelect(facility._id)}
                          />
                        </td>
                        <td className="px-4 py-4">
                          <div className="flex items-center gap-3 min-w-0">
                            <div className="flex-shrink-0">
                              {facility.images?.[0] ? (
                                <img
                                  src={facility.images[0]}
                                  alt={facility.name}
                                  className="w-12 h-12 rounded-lg object-cover border-2 border-gray-200"
                                />
                              ) : (
                                <div className="w-12 h-12 rounded-lg bg-gray-100 flex items-center justify-center">
                                  <Building className="h-6 w-6 text-gray-400" />
                                </div>
                              )}
                            </div>
                            <div className="min-w-0 flex-1">
                              <p
                                className="font-semibold text-gray-900 text-sm truncate"
                                title={facility.name}
                              >
                                {facility.name}
                              </p>
                              <div className="flex items-center gap-2 mt-1 flex-wrap">
                                <Badge variant="outline" className="text-xs">
                                  {facility.careTypes?.[0] || 'N/A'}
                                </Badge>
                                {facility.verified && (
                                  <Badge className="bg-blue-100 text-blue-700 text-xs border-blue-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="font-medium text-gray-900 flex items-center gap-1">
                              <User className="h-3 w-3 text-gray-400" />
                              {facility.ownerId?.firstName} {facility.ownerId?.lastName}
                            </p>
                            <p className="text-gray-500 text-xs mt-1 flex items-center gap-1">
                              <Mail className="h-3 w-3" />
                              {facility.ownerId?.email}
                            </p>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          <div className="text-sm">
                            <p className="text-gray-900 flex items-center gap-1">
                              <Phone className="h-3 w-3 text-gray-400" />
                              {facility.contact?.phone || facility.phone || facility.phoneNumber || 'N/A'}
                            </p>
                            <p className="text-gray-500 text-xs mt-1 flex items-center gap-1">
                              <Mail className="h-3 w-3" />
                              {facility.contact?.email || facility.email || 'N/A'}
                            </p>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          <div className="text-sm">
                            <p className="text-gray-900 flex items-center gap-1">
                              <MapPin className="h-3 w-3 text-gray-400" />
                              {facility.location?.city}, {facility.location?.state}
                            </p>
                            <p className="text-gray-500 text-xs mt-1">
                              {facility.location?.zipCode}
                            </p>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          <div className="text-sm">
                            {facility.featured ? (
                              <>
                                <Badge className="bg-gradient-to-r from-yellow-500 to-orange-500 text-white text-xs mb-1">
                                  <Star className="h-3 w-3 mr-1 fill-white" />
                                  Featured
                                </Badge>
                                {facility.featuredUntil && (
                                  <p className="text-gray-500 text-xs mt-1 flex items-center gap-1">
                                    <Clock className="h-3 w-3" />
                                    Until {formatDate(facility.featuredUntil)}
                                  </p>
                                )}
                              </>
                            ) : (
                              <span className="text-gray-400 text-xs">-</span>
                            )}
                          </div>
                        </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(facility.createdAt)}
                            </p>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          {getStatusBadge(facility.status)}
                        </td>
                        <td className="px-4 py-4">
                          <div className="flex items-center gap-1">
                            <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                            <span className="font-medium text-sm">{facility.rating?.toFixed(1) || '0.0'}</span>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => {
                                setSelectedFacility(facility)
                                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(facility)}
                                >
                                  <Edit className="h-4 w-4 mr-2 text-blue-600" />
                                  Edit Facility
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                {facility.status === 'pending' && (
                                  <>
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedFacility(facility)
                                        setShowApproveDialog(true)
                                      }}
                                    >
                                      <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                      Approve
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedFacility(facility)
                                        setShowRejectDialog(true)
                                      }}
                                    >
                                      <XSquare className="h-4 w-4 mr-2 text-red-600" />
                                      Reject
                                    </DropdownMenuItem>
                                  </>
                                )}
                                {facility.status === 'rejected' && (
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedFacility(facility)
                                      setShowApproveDialog(true)
                                    }}
                                  >
                                    <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                    Approve
                                  </DropdownMenuItem>
                                )}
                                {facility.status === 'active' && (
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedFacility(facility)
                                      setShowSuspendDialog(true)
                                    }}
                                  >
                                    <XCircle className="h-4 w-4 mr-2 text-orange-600" />
                                    Suspend
                                  </DropdownMenuItem>
                                )}
                                {facility.status === 'suspended' && (
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedFacility(facility)
                                      setShowApproveDialog(true)
                                    }}
                                  >
                                    <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                    Activate
                                  </DropdownMenuItem>
                                )}
                                {(facility.status === 'active' || facility.status === 'suspended') && (
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedFacility(facility)
                                      setShowCloseDialog(true)
                                    }}
                                  >
                                    <Building className="h-4 w-4 mr-2 text-gray-600" />
                                    Mark as Closed
                                  </DropdownMenuItem>
                                )}
                                {facility.status === 'closed' && (
                                  <DropdownMenuItem
                                    onClick={() => {
                                      setSelectedFacility(facility)
                                      setShowApproveDialog(true)
                                    }}
                                  >
                                    <CheckCircle className="h-4 w-4 mr-2 text-green-600" />
                                    Reopen Facility
                                  </DropdownMenuItem>
                                )}
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                  onClick={() => handleVerifyToggle(facility)}
                                >
                                  <ShieldCheck className="h-4 w-4 mr-2 text-blue-600" />
                                  {facility.verified ? 'Unverify' : 'Verify'}
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={() => {
                                    setSelectedFacility(facility)
                                    setShowFeaturedDialog(true)
                                  }}
                                >
                                  <Star className="h-4 w-4 mr-2 text-yellow-600" />
                                  {facility.featured ? 'Remove from Featured' : 'Make Featured'}
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                  onClick={() => {
                                    setSelectedFacility(facility)
                                    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 flex-col sm:flex-row items-center justify-between gap-3">
          <p className="text-xs md:text-sm text-gray-700">
            Page {currentPage} of {totalPages} • {facilities.length} facilities shown
          </p>
          <div className="flex items-center gap-1 md:gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={currentPage === 1 || loading}
              onClick={() => setCurrentPage(p => p - 1)}
              className="text-xs md:text-sm px-2 md:px-4"
            >
              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}
                  className="h-8 w-8 md:h-9 md:w-9 p-0"
                >
                  {pageNum}
                </Button>
              )
            })}
            <Button
              variant="outline"
              size="sm"
              disabled={currentPage === totalPages || loading}
              onClick={() => setCurrentPage(p => p + 1)}
              className="text-xs md:text-sm px-2 md:px-4"
            >
              Next
            </Button>
          </div>
        </div>
      </div>

      {/* View Facility 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>{selectedFacility?.name}</span>
              {selectedFacility?.verified && (
                <Badge className="bg-blue-100 text-blue-700 border-blue-200">
                  <ShieldCheck className="h-3 w-3 mr-1" />
                  Verified
                </Badge>
              )}
            </DialogTitle>
            <DialogDescription>
              Complete facility details and information
            </DialogDescription>
          </DialogHeader>

          {selectedFacility && (
            <div className="space-y-6 py-4">
              {/* Images */}
              <div>
                <h4 className="font-semibold mb-2 text-sm">Images</h4>
                {selectedFacility.images?.length > 0 ? (
                  <div className="grid grid-cols-3 gap-2">
                    {selectedFacility.images.slice(0, 6).map((img: string, i: number) => (
                      <img key={i} src={img} alt={`${selectedFacility.name} ${i + 1}`} className="w-full h-24 object-cover rounded-lg border-2 border-gray-200" />
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-400 italic">No images uploaded</p>
                )}
              </div>

              {/* Basic Info */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label className="text-xs text-gray-500">Status</Label>
                  <div className="mt-1">{getStatusBadge(selectedFacility.status)}</div>
                </div>
                <div>
                  <Label className="text-xs text-gray-500">Rating</Label>
                  <div className="flex items-center gap-1 mt-1">
                    <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                    <span className="font-medium">{selectedFacility.rating?.toFixed(1) || '0.0'}</span>
                  </div>
                </div>
                <div>
                  <Label className="text-xs text-gray-500">Verified</Label>
                  <p className="text-sm mt-1">{selectedFacility.verified ? 'Yes' : 'No'}</p>
                </div>
              </div>

              {/* Description */}
              <div>
                <Label className="text-xs text-gray-500">Description</Label>
                <p className="text-sm mt-1 text-gray-700">{selectedFacility.description || 'N/A'}</p>
              </div>

              {/* Facility ID */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs text-gray-500">Facility ID</Label>
                  <p className="text-sm mt-1">{selectedFacility.facilityId || 'N/A'}</p>
                </div>
                <div>
                  <Label className="text-xs text-gray-500">Data Source</Label>
                  <p className="text-sm mt-1">{selectedFacility.dataSource || 'Internal'}</p>
                </div>
              </div>

              {/* Claim Requests - Show if facility has pending claims */}
              {selectedFacility.claimStatus === 'claim_pending' && selectedFacility.claimRequests && selectedFacility.claimRequests.length > 0 && (
                <div className="border-t pt-4">
                  <div className="flex items-center justify-between mb-3">
                    <h4 className="font-semibold text-sm flex items-center gap-2">
                      <User className="h-4 w-4 text-purple-600" />
                      Pending Claim Requests ({selectedFacility.claimRequests.filter((c: any) => c.status === 'pending').length})
                    </h4>
                    {selectedFacility.claimRequests.some((c: any) => c.status === 'pending') && (
                      <Link href={`/admin/facilities/claims`}>
                        <Button size="sm" variant="outline">
                          <ExternalLink className="h-3 w-3 mr-1" />
                          Review Claims
                        </Button>
                      </Link>
                    )}
                  </div>

                  {selectedFacility.claimRequests
                    .filter((claim: any) => claim.status === 'pending')
                    .map((claim: any, index: number) => (
                      <div key={index} className="mb-4 p-4 border border-purple-200 rounded-lg bg-purple-50">
                        <div className="flex items-center justify-between mb-3">
                          <Badge className="bg-yellow-100 text-yellow-800 border-yellow-200">
                            <Clock className="h-3 w-3 mr-1" />
                            Pending Review
                          </Badge>
                          <span className="text-xs text-gray-500">
                            Submitted {new Date(claim.requestedAt).toLocaleDateString()}
                          </span>
                        </div>

                        {/* Claimant Contact Information */}
                        <div className="mb-3">
                          <h5 className="text-xs font-semibold text-purple-900 mb-2">Claimant Contact Information</h5>
                          <div className="grid grid-cols-2 gap-3 bg-white p-3 rounded border border-purple-100">
                            <div>
                              <Label className="text-xs text-gray-500">Full Name</Label>
                              <p className="text-sm font-medium text-gray-900 mt-0.5">
                                {claim.claimantInfo?.name || 'N/A'}
                              </p>
                            </div>
                            <div>
                              <Label className="text-xs text-gray-500">Email Address</Label>
                              <p className="text-sm font-medium text-gray-900 mt-0.5 flex items-center gap-1">
                                <Mail className="h-3 w-3 text-gray-400" />
                                {claim.userId?.email || 'N/A'}
                              </p>
                            </div>
                            <div>
                              <Label className="text-xs text-gray-500">Phone Number</Label>
                              <p className="text-sm font-medium text-gray-900 mt-0.5 flex items-center gap-1">
                                <Phone className="h-3 w-3 text-gray-400" />
                                {claim.claimantInfo?.phone || 'N/A'}
                              </p>
                            </div>
                            <div>
                              <Label className="text-xs text-gray-500">Position/Title</Label>
                              <p className="text-sm font-medium text-gray-900 mt-0.5">
                                {claim.claimantInfo?.position || 'N/A'}
                              </p>
                            </div>
                            <div>
                              <Label className="text-xs text-gray-500">Relationship</Label>
                              <p className="text-sm font-medium text-gray-900 mt-0.5 capitalize">
                                {claim.claimantInfo?.relationship?.replace(/_/g, ' ') || 'N/A'}
                              </p>
                            </div>
                            {claim.claimantInfo?.businessLicense && (
                              <div>
                                <Label className="text-xs text-gray-500">Business License Number</Label>
                                <p className="text-sm font-medium text-gray-900 mt-0.5 font-mono">
                                  {claim.claimantInfo.businessLicense}
                                </p>
                              </div>
                            )}
                          </div>
                        </div>

                        {/* Claim Message */}
                        <div className="mb-3">
                          <Label className="text-xs text-gray-500">Reason for Claim</Label>
                          <div className="bg-white p-3 rounded border border-purple-100 mt-1">
                            <p className="text-sm text-gray-900 whitespace-pre-wrap">
                              {claim.message || 'No message provided'}
                            </p>
                          </div>
                        </div>

                        {/* Supporting Documents */}
                        {claim.documents && claim.documents.length > 0 && (
                          <div>
                            <Label className="text-xs text-gray-500 mb-2 block">
                              Supporting Documents ({claim.documents.length})
                            </Label>
                            <div className="space-y-2">
                              {claim.documents.map((doc: any, docIndex: number) => (
                                <div key={docIndex} className="flex items-center justify-between p-2 bg-white border border-purple-100 rounded">
                                  <div className="flex items-center gap-2 flex-1 min-w-0">
                                    <FileText className="h-4 w-4 text-purple-600 flex-shrink-0" />
                                    <div className="min-w-0 flex-1">
                                      <p className="text-sm font-medium text-gray-900 truncate">
                                        {doc.name}
                                      </p>
                                      <p className="text-xs text-gray-500">
                                        {doc.type} • {doc.uploadedAt ? new Date(doc.uploadedAt).toLocaleDateString() : 'No date'}
                                      </p>
                                    </div>
                                  </div>
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    asChild
                                    className="flex-shrink-0"
                                  >
                                    <a
                                      href={doc.url}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      onClick={(e) => {
                                        // Verify URL exists
                                        if (!doc.url || doc.url === '') {
                                          e.preventDefault()
                                          toast.error('Document URL not available', { title: 'Error' })
                                        }
                                      }}
                                    >
                                      <Download className="h-3 w-3 mr-1" />
                                      View
                                    </a>
                                  </Button>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* User Info (Who submitted the claim) */}
                        {claim.userId && (
                          <div className="mt-3 pt-3 border-t border-purple-200">
                            <Label className="text-xs text-gray-500">Submitted by User</Label>
                            <p className="text-xs text-gray-600 mt-1">
                              User ID: <span className="font-mono">{claim.userId.toString()}</span>
                            </p>
                          </div>
                        )}

                        {/* Action Button */}
                        <div className="mt-3 pt-3 border-t border-purple-200">
                          <Link href={`/admin/facilities/claims/${selectedFacility._id}:${claim.userId}`}>
                            <Button className="w-full bg-purple-600 hover:bg-purple-700">
                              <CheckCircle className="h-4 w-4 mr-2" />
                              Review & Approve/Reject This Claim
                            </Button>
                          </Link>
                        </div>
                      </div>
                    ))}

                  {/* Show approved/rejected claims count if any */}
                  {selectedFacility.claimRequests.filter((c: any) => c.status !== 'pending').length > 0 && (
                    <p className="text-xs text-gray-500 mt-2">
                      {selectedFacility.claimRequests.filter((c: any) => c.status === 'approved').length} approved, {' '}
                      {selectedFacility.claimRequests.filter((c: any) => c.status === 'rejected').length} rejected
                    </p>
                  )}
                </div>
              )}

              {/* Owner Info */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Owner Information</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Name</Label>
                    <p className="text-sm mt-1">{selectedFacility.ownerId?.firstName && selectedFacility.ownerId?.lastName ? `${selectedFacility.ownerId.firstName} ${selectedFacility.ownerId.lastName}` : 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Email</Label>
                    <p className="text-sm mt-1">{selectedFacility.ownerId?.email || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Role</Label>
                    <p className="text-sm mt-1">{selectedFacility.ownerId?.role || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Owner Status</Label>
                    <p className="text-sm mt-1">{selectedFacility.ownerId?.status || 'N/A'}</p>
                  </div>
                </div>
              </div>

              {/* Contact Info */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Contact Information</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Phone</Label>
                    <p className="text-sm mt-1">{selectedFacility.contact?.phone || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Email</Label>
                    <p className="text-sm mt-1">{selectedFacility.contact?.email || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Website</Label>
                    {selectedFacility.contact?.website ? (
                      <a href={selectedFacility.contact.website} target="_blank" rel="noopener noreferrer" className="text-sm mt-1 text-blue-600 hover:underline block">
                        {selectedFacility.contact.website}
                      </a>
                    ) : (
                      <p className="text-sm mt-1">N/A</p>
                    )}
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Fax</Label>
                    <p className="text-sm mt-1">{selectedFacility.contact?.fax || selectedFacility.fax || 'Not provided'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Emergency Contact</Label>
                    <p className="text-sm mt-1">{selectedFacility.contact?.emergencyContact || selectedFacility.emergencyContact || 'Not provided'}</p>
                  </div>
                </div>
              </div>

              {/* Location */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Location Details</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="col-span-2">
                    <Label className="text-xs text-gray-500">Street Address</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.address || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">City</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.city || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">State</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.state || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">ZIP Code</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.zipCode || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">County</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.county || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">State Region</Label>
                    <p className="text-sm mt-1">{selectedFacility.location?.stateRegion || selectedFacility.stateRegion || 'Not specified'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Coordinates</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.location?.coordinates?.lat && selectedFacility.location?.coordinates?.lng
                        ? `${selectedFacility.location.coordinates.lat}, ${selectedFacility.location.coordinates.lng}`
                        : selectedFacility.coordinates?.lat && selectedFacility.coordinates?.lng
                          ? `${selectedFacility.coordinates.lat}, ${selectedFacility.coordinates.lng}`
                          : 'Not available'}
                    </p>
                  </div>
                </div>
              </div>

              {/* Licensing */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Licensing Information</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">License Number</Label>
                    <p className="text-sm mt-1">{selectedFacility.licensing?.licenseNumber || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">License Type</Label>
                    <p className="text-sm mt-1">{selectedFacility.licensing?.licenseType || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Expiration Date</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.licensing?.expirationDate)}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Effective Date</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.licensing?.effectiveDate) || formatDate(selectedFacility.effectiveDate) || 'Not specified'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Initial License Date</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.licensing?.initialLicenseDate) || formatDate(selectedFacility.initialLicenseDate) || 'Not specified'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Licensed</Label>
                    <p className="text-sm mt-1">{selectedFacility.licensing?.facilityLicensed ? 'Yes' : 'No'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Certified</Label>
                    <p className="text-sm mt-1">{selectedFacility.licensing?.facilityCertified ? 'Yes' : 'No'}</p>
                  </div>
                </div>
              </div>

              {/* Capacity */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Capacity Information</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Total Licensed</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.capacity?.totalLicensed || selectedFacility.totalLicensed || selectedFacility.capacity?.total || 'Not specified'}
                      {(selectedFacility.capacity?.totalLicensed || selectedFacility.totalLicensed || selectedFacility.capacity?.total) ? ' beds' : ''}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Available Beds</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.capacity?.available || selectedFacility.availableCapacity || 'Not specified'}
                      {(selectedFacility.capacity?.available || selectedFacility.availableCapacity) ? ' beds' : ''}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Occupancy Rate</Label>
                    <p className="text-sm mt-1">
                      {(() => {
                        const total = selectedFacility.capacity?.totalLicensed || selectedFacility.totalLicensed || selectedFacility.capacity?.total;
                        const available = selectedFacility.capacity?.available || selectedFacility.availableCapacity;
                        return total && available && total > 0
                          ? `${Math.round(((total - available) / total) * 100)}%`
                          : 'Not calculated';
                      })()}
                    </p>
                  </div>
                </div>
              </div>

              {/* Care Types */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Care Types Offered</h4>
                {selectedFacility.careTypes?.length > 0 ? (
                  <div className="flex flex-wrap gap-2">
                    {selectedFacility.careTypes.map((type: string, i: number) => (
                      <Badge key={i} variant="outline">{type}</Badge>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-400">N/A</p>
                )}
              </div>

              {/* Amenities */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Amenities</h4>
                {(selectedFacility.amenities?.length > 0 || selectedFacility.services?.amenities?.length > 0) ? (
                  <div className="flex flex-wrap gap-2">
                    {(selectedFacility.amenities || selectedFacility.services?.amenities || []).map((amenity: string, i: number) => (
                      <Badge key={i} variant="secondary">{amenity}</Badge>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-400">No amenities listed</p>
                )}
              </div>

              {/* Medical Services */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Medical Services</h4>
                {(selectedFacility.medicalServices?.length > 0 || selectedFacility.services?.medicalServices?.length > 0) ? (
                  <div className="flex flex-wrap gap-2">
                    {(selectedFacility.medicalServices || selectedFacility.services?.medicalServices || []).map((service: string, i: number) => (
                      <Badge key={i} variant="secondary">{service}</Badge>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-400">No medical services listed</p>
                )}
              </div>

              {/* Pricing */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Pricing Information</h4>
                {(selectedFacility.pricing?.min && selectedFacility.pricing?.max) || (selectedFacility.minPrice && selectedFacility.maxPrice) ? (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label className="text-xs text-gray-500">Price Range</Label>
                      <p className="text-sm mt-1">
                        ${(selectedFacility.pricing?.min || selectedFacility.minPrice)?.toLocaleString()} - ${(selectedFacility.pricing?.max || selectedFacility.maxPrice)?.toLocaleString()}
                      </p>
                    </div>
                    <div>
                      <Label className="text-xs text-gray-500">Period</Label>
                      <p className="text-sm mt-1">{selectedFacility.pricing?.period || 'Monthly'}</p>
                    </div>
                    <div className="col-span-2">
                      <Label className="text-xs text-gray-500">Pricing Details</Label>
                      <p className="text-sm mt-1">{selectedFacility.pricing?.details || selectedFacility.pricingDetails || 'Standard pricing applies'}</p>
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-gray-400">Pricing information not available</p>
                )}
              </div>

              {/* Additional Information */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Additional Information</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Program Type</Label>
                    <p className="text-sm mt-1">{selectedFacility.programType || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Featured</Label>
                    <p className="text-sm mt-1">{selectedFacility.featured ? 'Yes' : 'No'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Featured Until</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.featuredUntil) || 'Not featured'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">View Count</Label>
                    <p className="text-sm mt-1">{selectedFacility.viewCount || '0'}</p>
                  </div>
                </div>
              </div>

              {/* Dates */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Important Dates</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Created / Submitted</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.createdAt)}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Last Updated</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.updatedAt) || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Submitted At</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.submittedAt) || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Approved At</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.approvedAt) || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Rejected At</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.rejectedAt) || 'N/A'}</p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Last Synced</Label>
                    <p className="text-sm mt-1">{formatDate(selectedFacility.lastSyncedAt) || 'N/A'}</p>
                  </div>
                </div>
              </div>

              {/* Rejection/Suspension Reason */}
              {(selectedFacility.rejectionReason || selectedFacility.suspensionReason) && (
                <div className="border-t pt-4">
                  <h4 className="font-semibold mb-3 text-sm">Admin Notes</h4>
                  {selectedFacility.rejectionReason && (
                    <div className="mb-3">
                      <Label className="text-xs text-red-600">Rejection Reason</Label>
                      <p className="text-sm mt-1 text-red-700 bg-red-50 p-3 rounded">
                        {selectedFacility.rejectionReason}
                      </p>
                    </div>
                  )}
                  {selectedFacility.suspensionReason && (
                    <div>
                      <Label className="text-xs text-orange-600">Suspension Reason</Label>
                      <p className="text-sm mt-1 text-orange-700 bg-orange-50 p-3 rounded">
                        {selectedFacility.suspensionReason}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Admin Actions History */}
              <div className="border-t pt-4">
                <h4 className="font-semibold mb-3 text-sm">Admin Action History</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs text-gray-500">Approved By</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.approvedBy ?
                        `${selectedFacility.approvedBy.firstName} ${selectedFacility.approvedBy.lastName}` :
                        'N/A'}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Rejected By</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.rejectedBy ?
                        `${selectedFacility.rejectedBy.firstName} ${selectedFacility.rejectedBy.lastName}` :
                        'N/A'}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs text-gray-500">Last Modified By</Label>
                    <p className="text-sm mt-1">
                      {selectedFacility.lastModifiedBy ?
                        `${selectedFacility.lastModifiedBy.firstName} ${selectedFacility.lastModifiedBy.lastName}` :
                        'N/A'}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

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

      {/* Approve Dialog */}
      <AlertDialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Approve Facility?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to approve <strong>{selectedFacility?.name}</strong>?
              The facility owner will be notified via email and the facility 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>

      {/* Reject Dialog */}
      <Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject Facility</DialogTitle>
            <DialogDescription>
              Please provide a reason for rejecting <strong>{selectedFacility?.name}</strong>.
              This reason will be sent to the facility owner.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <Label htmlFor="reject-reason">Rejection Reason *</Label>
            <Textarea
              id="reject-reason"
              value={actionReason}
              onChange={(e) => setActionReason(e.target.value)}
              placeholder="Please explain why this facility is being rejected..."
              rows={4}
              className="mt-2"
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowRejectDialog(false)
              setActionReason("")
            }} disabled={actionLoading}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleReject} disabled={actionLoading || !actionReason.trim()}>
              {actionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <XSquare className="h-4 w-4 mr-2" />}
              Reject
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Suspend Dialog */}
      <Dialog open={showSuspendDialog} onOpenChange={setShowSuspendDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Suspend Facility</DialogTitle>
            <DialogDescription>
              Please provide a reason for suspending <strong>{selectedFacility?.name}</strong>.
              The facility will be removed from public 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 facility 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>

      {/* Edit Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Facility: {selectedFacility?.name}</DialogTitle>
            <DialogDescription>
              Update facility information. Changes will be saved immediately.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 py-4">
            {/* Basic Information */}
            <div className="space-y-4">
              <h4 className="font-semibold text-sm">Basic Information</h4>
              <div>
                <Label htmlFor="edit-name">Facility Name *</Label>
                <Input
                  id="edit-name"
                  value={editForm.name}
                  onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
                  placeholder="Facility name"
                />
              </div>
              <div>
                <Label htmlFor="edit-description">Description</Label>
                <Textarea
                  id="edit-description"
                  value={editForm.description}
                  onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                  placeholder="Facility description..."
                  rows={4}
                />
              </div>
            </div>

            {/* Contact Information */}
            <div className="space-y-4 border-t pt-4">
              <h4 className="font-semibold text-sm">Contact Information</h4>
              <div className="grid grid-cols-2 gap-4">
                <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>
                  <Label htmlFor="edit-email">Email *</Label>
                  <Input
                    id="edit-email"
                    type="email"
                    value={editForm.email}
                    onChange={(e) => setEditForm({ ...editForm, email: e.target.value })}
                    placeholder="contact@facility.com"
                  />
                </div>
              </div>
              <div>
                <Label htmlFor="edit-website">Website</Label>
                <Input
                  id="edit-website"
                  type="url"
                  value={editForm.website}
                  onChange={(e) => setEditForm({ ...editForm, website: e.target.value })}
                  placeholder="https://www.facility.com"
                />
              </div>
            </div>

            {/* Location */}
            <div className="space-y-4 border-t pt-4">
              <h4 className="font-semibold text-sm">Location</h4>
              <div>
                <Label htmlFor="edit-address">Street Address</Label>
                <Input
                  id="edit-address"
                  value={editForm.address}
                  onChange={(e) => setEditForm({ ...editForm, address: e.target.value })}
                  placeholder="123 Main St"
                />
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="edit-city">City</Label>
                  <Input
                    id="edit-city"
                    value={editForm.city}
                    onChange={(e) => setEditForm({ ...editForm, city: e.target.value })}
                    placeholder="City"
                  />
                </div>
                <div>
                  <Label htmlFor="edit-state">State</Label>
                  <Input
                    id="edit-state"
                    value={editForm.state}
                    onChange={(e) => setEditForm({ ...editForm, state: e.target.value })}
                    placeholder="TX"
                    maxLength={2}
                  />
                </div>
                <div>
                  <Label htmlFor="edit-zipCode">ZIP Code</Label>
                  <Input
                    id="edit-zipCode"
                    value={editForm.zipCode}
                    onChange={(e) => setEditForm({ ...editForm, zipCode: e.target.value })}
                    placeholder="78701"
                  />
                </div>
              </div>
            </div>

            {/* Licensing & Capacity */}
            <div className="space-y-4 border-t pt-4">
              <h4 className="font-semibold text-sm">Licensing & Capacity</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="edit-license">License Number</Label>
                  <Input
                    id="edit-license"
                    value={editForm.licenseNumber}
                    onChange={(e) => setEditForm({ ...editForm, licenseNumber: e.target.value })}
                    placeholder="ALF-12345"
                  />
                </div>
                <div>
                  <Label htmlFor="edit-capacity">Total Capacity (beds)</Label>
                  <Input
                    id="edit-capacity"
                    type="number"
                    min="1"
                    value={editForm.totalCapacity}
                    onChange={(e) => setEditForm({ ...editForm, totalCapacity: e.target.value })}
                    placeholder="50"
                  />
                </div>
              </div>
            </div>

            {/* Care Types */}
            <div className="space-y-4 border-t pt-4">
              <h4 className="font-semibold text-sm">Care Types</h4>
              <div className="grid grid-cols-2 gap-3">
                {['Assisted Living', 'Memory Care', 'Independent Living', 'Skilled Nursing', 'Respite Care', 'Hospice Care'].map((type) => (
                  <div key={type} className="flex items-center space-x-2">
                    <Checkbox
                      id={`edit-care-${type}`}
                      checked={editForm.careTypes.includes(type)}
                      onCheckedChange={(checked) => {
                        if (checked) {
                          setEditForm({ ...editForm, careTypes: [...editForm.careTypes, type] })
                        } else {
                          setEditForm({ ...editForm, careTypes: editForm.careTypes.filter((t: string) => t !== type) })
                        }
                      }}
                    />
                    <Label htmlFor={`edit-care-${type}`} className="text-sm font-normal cursor-pointer">
                      {type}
                    </Label>
                  </div>
                ))}
              </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>

      {/* Close Facility Dialog */}
      <AlertDialog open={showCloseDialog} onOpenChange={setShowCloseDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <Building className="h-5 w-5 text-gray-600" />
              Close Facility?
            </AlertDialogTitle>
            <AlertDialogDescription>
              Mark <strong>{selectedFacility?.name}</strong> as permanently closed. The facility will be hidden from public view but data will be retained.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <div className="py-4">
            <Label htmlFor="close-reason" className="text-sm font-semibold">
              Reason for Closing <span className="text-red-500">*</span>
            </Label>
            <Textarea
              id="close-reason"
              value={actionReason}
              onChange={(e) => setActionReason(e.target.value)}
              placeholder="e.g., Facility permanently closed operations, Business shut down, etc."
              className="mt-2 min-h-[100px]"
              disabled={actionLoading}
            />
          </div>

          <AlertDialogFooter>
            <AlertDialogCancel
              disabled={actionLoading}
              onClick={() => setActionReason("")}
            >
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleClose}
              disabled={actionLoading || !actionReason.trim()}
              className="bg-gray-600 hover:bg-gray-700"
            >
              {actionLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Closing...
                </>
              ) : (
                <>
                  <Building className="h-4 w-4 mr-2" />
                  Mark as Closed
                </>
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Featured Toggle Dialog */}
      <Dialog open={showFeaturedDialog} onOpenChange={setShowFeaturedDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Star className="h-5 w-5 text-yellow-600" />
              {selectedFacility?.featured ? 'Remove from Featured' : 'Make Featured'}
            </DialogTitle>
            <DialogDescription>
              {selectedFacility?.featured
                ? `Remove ${selectedFacility?.name} from featured listings?`
                : `Add ${selectedFacility?.name} to featured listings?`
              }
            </DialogDescription>
          </DialogHeader>

          {!selectedFacility?.featured && (
            <div className="py-4">
              <Label htmlFor="featured-until" className="text-sm font-semibold">
                Featured Until (Optional)
              </Label>
              <Input
                id="featured-until"
                type="date"
                value={featuredUntilDate}
                onChange={(e) => setFeaturedUntilDate(e.target.value)}
                min={new Date().toISOString().split('T')[0]}
                className="mt-2"
                disabled={actionLoading}
              />
              <p className="text-xs text-gray-500 mt-2">
                Leave empty to feature indefinitely
              </p>
            </div>
          )}

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setShowFeaturedDialog(false)
                setFeaturedUntilDate("")
              }}
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleToggleFeatured}
              disabled={actionLoading}
              className="bg-yellow-600 hover:bg-yellow-700"
            >
              {actionLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Updating...
                </>
              ) : (
                <>
                  <Star className="h-4 w-4 mr-2" />
                  {selectedFacility?.featured ? 'Remove' : 'Make Featured'}
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Facility Permanently?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to permanently delete <strong>{selectedFacility?.name}</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>
    </div>
  )
}