import { getUsers } from '@/lib/actions/users'
import { getCompanies } from '@/lib/actions/companies'
import { UserList } from '@/components/admin/user-list'
import { UserDialog } from '@/components/admin/user-dialog'
import { Users } from 'lucide-react'
import { Suspense } from 'react'

export const dynamic = 'force-dynamic'

export default async function AdminUsersPage() {
  return (
    <div className="flex-1 space-y-8 p-8 pt-6">
      <div className="flex items-center justify-between space-y-2">
        <div>
          <h2 className="text-3xl font-bold tracking-tight text-gradient flex items-center gap-3">
            <Users className="w-8 h-8 text-primary" />
            Benutzerverwaltung
          </h2>
          <p className="text-slate-400">
            Verwalten Sie Benutzerkonten, Berechtigungen und Sicherheit.
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <UserDialog />
        </div>
      </div>
      <Suspense fallback={<div className="h-40 w-full animate-pulse bg-white/5 rounded-xl" />}>
        <UserDataWrapper />
      </Suspense>
    </div>
  )
}

async function UserDataWrapper() {
  try {
    const [users, companies] = await Promise.all([getUsers(), getCompanies()])
    return <UserList initialUsers={users} companies={companies} />
  } catch (error: any) {
    console.error('[UserDataWrapper] Error loading users:', error)
    return (
      <div className="p-8 border border-destructive/50 bg-destructive/10 rounded-xl text-destructive text-center space-y-2">
        <p>Fehler beim Laden der Benutzer. Stellen Sie sicher, dass der SERVICE_ROLE_KEY korrekt konfiguriert ist.</p>
        <p className="text-xs font-mono text-destructive/80">
          Details: {error instanceof Error ? error.message : JSON.stringify(error)}
        </p>
      </div>
    )
  }
}
