<script setup lang="ts">
const auth = useAuthStore()
const toast = useToast()
const router = useRouter()

type AdminRole = {
  id: string
  name: string
  description?: string | null
  tenant_id: number | null
}

type AdminTenant = {
  id: number
  name: string
  short: string
  user_count: number
  locked?: string | null
}

type AdminUserProfile = {
  id: string
  user_id: string
  tenant_id: number
  full_name: string | null
  first_name: string
  last_name: string
  email?: string | null
  active: boolean
}

type AdminUser = {
  id: string
  email: string
  display_name: string
  multiTenant: boolean
  must_change_password: boolean
  is_admin: boolean
  profile_defaults: {
    first_name: string
    last_name: string
  }
  tenant_ids: number[]
  role_assignments: { tenant_id: number; role_id: string }[]
  profile_assignments?: { tenant_id: number; profile_id?: string | null }[]
  profiles: AdminUserProfile[]
}

const loading = ref(true)
const savingUser = ref(false)
const savingTenant = ref(false)
const creatingUser = ref(false)
const creatingTenant = ref(false)
const activeTab = ref(0)
const createUserModalOpen = ref(false)
const createTenantModalOpen = ref(false)
const createdUserPassword = ref("")

const users = ref<AdminUser[]>([])
const tenants = ref<AdminTenant[]>([])
const roles = ref<AdminRole[]>([])
const unassignedProfiles = ref<AdminUserProfile[]>([])

const selectedUserId = ref<string | null>(null)
const selectedTenantId = ref<number | null>(null)

const userForm = ref<AdminUser | null>(null)
const tenantForm = ref<AdminTenant | null>(null)
const createUserForm = ref({
  email: "",
  password: "",
  first_name: "",
  last_name: "",
  is_admin: false,
  multiTenant: true,
})
const createTenantForm = ref({
  name: "",
  short: "",
})

const tabItems = [
  { label: "Benutzer" },
  { label: "Tenants" },
]

const sortedUsers = computed(() =>
  [...users.value].sort((a, b) => a.display_name.localeCompare(b.display_name, "de"))
)

const sortedTenants = computed(() =>
  [...tenants.value].sort((a, b) => a.name.localeCompare(b.name, "de"))
)

const tenantOptions = computed(() =>
  sortedTenants.value.map((tenant) => ({
    label: `${tenant.name} (${tenant.short})`,
    value: tenant.id,
  }))
)

const userTableColumns = [
  { key: "display_name", label: "Benutzer" },
  { key: "email", label: "E-Mail" },
  { key: "tenant_count", label: "Tenants" },
  { key: "is_admin", label: "Admin" },
]

const tenantTableColumns = [
  { key: "name", label: "Tenant" },
  { key: "short", label: "Kürzel" },
  { key: "user_count", label: "Benutzer" },
]

const userTableRows = computed(() =>
  sortedUsers.value.map((user) => ({
    ...user,
    tenant_count: user.tenant_ids.length,
    is_admin: user.is_admin ? "Ja" : "Nein",
  }))
)

const tenantTableRows = computed(() => sortedTenants.value)

const getRoleOptionsForTenant = (tenantId: number) =>
  roles.value
    .filter((role) => role.tenant_id === null || role.tenant_id === tenantId)
    .map((role) => ({
      label: role.tenant_id === null ? `${role.name} (global)` : role.name,
      value: role.id,
    }))

const getUsersForTenant = (tenantId: number) =>
  sortedUsers.value.filter((user) => user.tenant_ids.includes(tenantId))

const getFreeProfilesForTenant = (tenantId: number) =>
  unassignedProfiles.value.filter((profile) => profile.tenant_id === tenantId)

const cloneUser = (user: AdminUser): AdminUser => ({
  ...user,
  profile_defaults: { ...user.profile_defaults },
  tenant_ids: [...(user.tenant_ids || [])],
  role_assignments: [...(user.role_assignments || [])],
  profile_assignments: [...(user.profile_assignments || [])],
  profiles: [...(user.profiles || [])],
})

const cloneTenant = (tenant: AdminTenant): AdminTenant => ({
  ...tenant,
})

const normalizeUserAssignments = () => {
  if (!userForm.value) return

  const uniqueTenantIds = Array.from(new Set((userForm.value.tenant_ids || []).map(Number))).sort((a, b) => a - b)
  const assignmentsByTenant = new Map<number, string>()
  const profileAssignmentByTenant = new Map<number, string | null>()

  for (const assignment of userForm.value.role_assignments || []) {
    if (!uniqueTenantIds.includes(Number(assignment.tenant_id))) continue
    if (assignmentsByTenant.has(Number(assignment.tenant_id))) continue
    assignmentsByTenant.set(Number(assignment.tenant_id), assignment.role_id)
  }

  for (const assignment of userForm.value.profile_assignments || []) {
    if (!uniqueTenantIds.includes(Number(assignment.tenant_id))) continue
    profileAssignmentByTenant.set(Number(assignment.tenant_id), assignment.profile_id || null)
  }

  userForm.value.tenant_ids = uniqueTenantIds
  userForm.value.role_assignments = uniqueTenantIds
    .map((tenantId) => {
      const roleId = assignmentsByTenant.get(tenantId)
      return roleId ? { tenant_id: tenantId, role_id: roleId } : null
    })
    .filter(Boolean) as { tenant_id: number; role_id: string }[]
  userForm.value.profile_assignments = uniqueTenantIds.map((tenantId) => ({
    tenant_id: tenantId,
    profile_id: profileAssignmentByTenant.get(tenantId) || null,
  }))
}

const updateUserTenants = (tenantIds: number[] = []) => {
  if (!userForm.value) return

  userForm.value.tenant_ids = tenantIds
  normalizeUserAssignments()
}

const setRoleForTenant = (tenantId: number, roleId?: string | null) => {
  if (!userForm.value) return

  userForm.value.role_assignments = (userForm.value.role_assignments || []).filter((assignment) => assignment.tenant_id !== tenantId)

  if (roleId) {
    userForm.value.role_assignments.push({
      tenant_id: tenantId,
      role_id: roleId,
    })
  }
}

const getRoleForTenant = (tenantId: number) => {
  return userForm.value?.role_assignments?.find((assignment) => assignment.tenant_id === tenantId)?.role_id || null
}

const setProfileAssignmentForTenant = (tenantId: number, profileId?: string | null) => {
  if (!userForm.value) return

  userForm.value.profile_assignments = (userForm.value.profile_assignments || []).filter((assignment) => assignment.tenant_id !== tenantId)
  userForm.value.profile_assignments.push({
    tenant_id: tenantId,
    profile_id: profileId || null,
  })
}

const getProfileAssignmentForTenant = (tenantId: number) => {
  return userForm.value?.profile_assignments?.find((assignment) => assignment.tenant_id === tenantId)?.profile_id || null
}

const selectUser = (row: any) => {
  const user = users.value.find((entry) => entry.id === row.id)
  if (!user) return

  selectedUserId.value = user.id
  userForm.value = cloneUser(user)
  normalizeUserAssignments()
}

const selectTenant = (row: any) => {
  const tenant = tenants.value.find((entry) => entry.id === row.id)
  if (!tenant) return

  selectedTenantId.value = tenant.id
  tenantForm.value = cloneTenant(tenant)
}

const fetchOverview = async () => {
  loading.value = true

  try {
    const response = await useNuxtApp().$api("/api/admin/overview")

    users.value = response.users || []
    tenants.value = response.tenants || []
    roles.value = response.roles || []
    unassignedProfiles.value = response.unassignedProfiles || []

    if (!selectedUserId.value && users.value.length) {
      selectUser(users.value[0])
    } else if (selectedUserId.value) {
      const currentUser = users.value.find((user) => user.id === selectedUserId.value)
      if (currentUser) selectUser(currentUser)
    }

    if (!selectedTenantId.value && tenants.value.length) {
      selectTenant(tenants.value[0])
    } else if (selectedTenantId.value) {
      const currentTenant = tenants.value.find((tenant) => tenant.id === selectedTenantId.value)
      if (currentTenant) selectTenant(currentTenant)
    }
  } catch (err: any) {
    console.error("[admin/fetchOverview]", err)
    toast.add({
      title: "Administration konnte nicht geladen werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    loading.value = false
  }
}

const saveUser = async () => {
  if (!userForm.value || savingUser.value) return

  savingUser.value = true
  normalizeUserAssignments()

  try {
    await useNuxtApp().$api(`/api/admin/users/${userForm.value.id}`, {
      method: "PUT",
      body: {
        email: userForm.value.email,
        multiTenant: userForm.value.multiTenant,
        must_change_password: userForm.value.must_change_password,
        is_admin: userForm.value.is_admin,
      },
    })

    await useNuxtApp().$api(`/api/admin/users/${userForm.value.id}/access`, {
      method: "PUT",
      body: {
        tenant_ids: userForm.value.tenant_ids,
        role_assignments: userForm.value.role_assignments,
        profile_defaults: userForm.value.profile_defaults,
        profile_assignments: userForm.value.profile_assignments,
      },
    })

    await fetchOverview()
    await auth.fetchMe()

    toast.add({
      title: "Benutzer gespeichert",
      color: "green",
    })
  } catch (err: any) {
    console.error("[admin/saveUser]", err)
    toast.add({
      title: "Benutzer konnte nicht gespeichert werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    savingUser.value = false
  }
}

const createUser = async () => {
  if (creatingUser.value) return

  creatingUser.value = true

  try {
    const response = await useNuxtApp().$api("/api/admin/users", {
      method: "POST",
      body: createUserForm.value,
    })

    createdUserPassword.value = response.initialPassword || ""
    createUserModalOpen.value = false
    createUserForm.value = {
      email: "",
      password: "",
      first_name: "",
      last_name: "",
      is_admin: false,
      multiTenant: true,
    }

    await fetchOverview()

    if (response.user?.id) {
      const createdUser = users.value.find((user) => user.id === response.user.id)
      if (createdUser) selectUser(createdUser)
    }

    toast.add({
      title: "Benutzer angelegt",
      description: createdUserPassword.value ? `Initialpasswort: ${createdUserPassword.value}` : undefined,
      color: "green",
    })
  } catch (err: any) {
    console.error("[admin/createUser]", err)
    toast.add({
      title: "Benutzer konnte nicht angelegt werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    creatingUser.value = false
  }
}

const saveTenant = async () => {
  if (!tenantForm.value || savingTenant.value) return

  savingTenant.value = true

  try {
    await useNuxtApp().$api(`/api/admin/tenants/${tenantForm.value.id}`, {
      method: "PUT",
      body: {
        name: tenantForm.value.name,
        short: tenantForm.value.short,
      },
    })

    await fetchOverview()
    await auth.fetchMe()

    toast.add({
      title: "Tenant gespeichert",
      color: "green",
    })
  } catch (err: any) {
    console.error("[admin/saveTenant]", err)
    toast.add({
      title: "Tenant konnte nicht gespeichert werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    savingTenant.value = false
  }
}

const createTenant = async () => {
  if (creatingTenant.value) return

  creatingTenant.value = true

  try {
    const response = await useNuxtApp().$api("/api/admin/tenants", {
      method: "POST",
      body: createTenantForm.value,
    })

    createTenantModalOpen.value = false
    createTenantForm.value = {
      name: "",
      short: "",
    }

    await fetchOverview()

    if (response.tenant?.id) {
      const createdTenant = tenants.value.find((tenant) => tenant.id === response.tenant.id)
      if (createdTenant) selectTenant(createdTenant)
    }

    toast.add({
      title: "Tenant angelegt",
      description: "Standardordner und Datei-Tags wurden erstellt.",
      color: "green",
    })
  } catch (err: any) {
    console.error("[admin/createTenant]", err)
    toast.add({
      title: "Tenant konnte nicht angelegt werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    creatingTenant.value = false
  }
}

onMounted(async () => {
  if (!auth.user?.is_admin) {
    toast.add({
      title: "Zugriff verweigert",
      description: "Diese Seite ist nur für administrative Benutzer verfügbar.",
      color: "red",
    })
    await router.push("/")
    return
  }

  await fetchOverview()
})
</script>

<template>
  <UDashboardNavbar title="Administration" />

  <UDashboardPanelContent class="p-5 overflow-hidden">
    <UAlert
      v-if="!auth.user?.is_admin"
      title="Kein Zugriff"
      description="Für diese Seite wird ein administrativer Benutzer benötigt."
      color="red"
      variant="soft"
    />

    <UTabs
      v-else
      v-model="activeTab"
      :items="tabItems"
      class="admin-tabs h-full"
    >
      <template #item="{ item }">
        <div v-if="item.label === 'Benutzer'" class="admin-grid mt-5 grid grid-cols-1 xl:grid-cols-3 gap-5">
          <UCard class="admin-card xl:col-span-1">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-lg font-semibold">Benutzer</h2>
              <div class="flex items-center gap-2">
                <UBadge variant="subtle">{{ users.length }}</UBadge>
                <UButton
                  size="sm"
                  icon="i-heroicons-plus"
                  @click="createUserModalOpen = true"
                >
                  Benutzer
                </UButton>
              </div>
            </div>

            <div class="admin-scroll">
              <UTable
                v-if="!loading"
                :rows="userTableRows"
                :columns="userTableColumns"
                @select="selectUser"
              />

              <USkeleton v-else class="h-80" />
            </div>
          </UCard>

          <UCard class="admin-card xl:col-span-2">
            <div v-if="userForm" class="admin-scroll space-y-6">
              <div class="flex items-start justify-between gap-4">
                <div>
                  <h2 class="text-lg font-semibold">{{ userForm.display_name }}</h2>
                  <p class="text-sm text-gray-500">{{ userForm.email }}</p>
                </div>

                <UButton
                  color="primary"
                  :loading="savingUser"
                  @click="saveUser"
                >
                  Benutzer speichern
                </UButton>
              </div>

              <UForm :state="userForm" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <UFormGroup label="E-Mail">
                  <UInput v-model="userForm.email" />
                </UFormGroup>

                <UFormGroup label="Profil Vorname">
                  <UInput v-model="userForm.profile_defaults.first_name" />
                </UFormGroup>

                <UFormGroup label="Profil Nachname">
                  <UInput v-model="userForm.profile_defaults.last_name" />
                </UFormGroup>

                <UFormGroup label="Tenants">
                  <USelectMenu
                    :model-value="userForm.tenant_ids"
                    :options="tenantOptions"
                    value-attribute="value"
                    option-attribute="label"
                    multiple
                    @update:model-value="updateUserTenants"
                  />
                </UFormGroup>

                <UFormGroup label="Administrative Freigabe">
                  <div class="flex items-center gap-3 h-10">
                    <UToggle v-model="userForm.is_admin" />
                    <span class="text-sm text-gray-600">Darf Administrationsseite und Admin-API nutzen</span>
                  </div>
                </UFormGroup>

                <UFormGroup label="Multi-Tenant">
                  <div class="flex items-center gap-3 h-10">
                    <UToggle v-model="userForm.multiTenant" />
                    <span class="text-sm text-gray-600">Benutzer darf mehreren Tenants zugeordnet sein</span>
                  </div>
                </UFormGroup>

                <UFormGroup label="Passwortwechsel erzwingen">
                  <div class="flex items-center gap-3 h-10">
                    <UToggle v-model="userForm.must_change_password" />
                    <span class="text-sm text-gray-600">Beim nächsten Login muss das Passwort geändert werden</span>
                  </div>
                </UFormGroup>
              </UForm>

              <div>
                <UDivider label="Rollen pro Tenant" class="mb-4" />

                <div
                  v-if="userForm.tenant_ids.length"
                  class="grid grid-cols-1 md:grid-cols-2 gap-4"
                >
                  <UCard
                    v-for="tenantId in userForm.tenant_ids"
                    :key="tenantId"
                    class="border border-gray-200"
                  >
                    <div class="space-y-3">
                      <div>
                        <div class="font-medium">
                          {{ tenants.find((tenant) => tenant.id === tenantId)?.name || `Tenant ${tenantId}` }}
                        </div>
                        <div class="text-sm text-gray-500">
                          {{ tenants.find((tenant) => tenant.id === tenantId)?.short || "" }}
                        </div>
                      </div>

                      <UFormGroup label="Rolle">
                        <USelectMenu
                          :model-value="getRoleForTenant(tenantId)"
                          :options="getRoleOptionsForTenant(tenantId)"
                          value-attribute="value"
                          option-attribute="label"
                          placeholder="Rolle auswählen"
                          @update:model-value="(value) => setRoleForTenant(tenantId, value)"
                        />
                      </UFormGroup>

                      <UFormGroup label="Freies Profil">
                        <USelectMenu
                          :model-value="getProfileAssignmentForTenant(tenantId)"
                          :options="[
                            { label: 'Neues Profil erzeugen', value: null },
                            ...getFreeProfilesForTenant(tenantId).map((profile) => ({
                              label: profile.full_name || `${profile.first_name} ${profile.last_name}`,
                              value: profile.id,
                            }))
                          ]"
                          value-attribute="value"
                          option-attribute="label"
                          placeholder="Profil auswählen"
                          @update:model-value="(value) => setProfileAssignmentForTenant(tenantId, value)"
                        />
                      </UFormGroup>
                    </div>
                  </UCard>
                </div>

                <UAlert
                  v-else
                  title="Keine Tenant-Zuordnung"
                  description="Weise dem Benutzer zuerst mindestens einen Tenant zu."
                  color="amber"
                  variant="soft"
                />
              </div>

              <div>
                <UDivider label="Profile im System" class="mb-4" />
                <div class="flex flex-wrap gap-2">
                  <UBadge
                    v-for="profile in userForm.profiles"
                    :key="profile.id"
                    variant="subtle"
                    color="gray"
                  >
                    {{ profile.full_name || `${profile.first_name} ${profile.last_name}` }} · Tenant {{ profile.tenant_id }}
                  </UBadge>
                </div>
              </div>
            </div>

            <UAlert
              v-else-if="!loading"
              title="Kein Benutzer ausgewählt"
              description="Wähle links einen Benutzer aus, um seine Zuordnungen zu bearbeiten."
              color="gray"
              variant="soft"
            />

            <div v-else class="admin-scroll">
              <USkeleton class="h-80" />
            </div>
          </UCard>
        </div>

        <div v-else-if="item.label === 'Tenants'" class="admin-grid mt-5 grid grid-cols-1 xl:grid-cols-3 gap-5">
          <UCard class="admin-card xl:col-span-1">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-lg font-semibold">Tenants</h2>
              <div class="flex items-center gap-2">
                <UBadge variant="subtle">{{ tenants.length }}</UBadge>
                <UButton
                  size="sm"
                  icon="i-heroicons-plus"
                  @click="createTenantModalOpen = true"
                >
                  Tenant
                </UButton>
              </div>
            </div>

            <div class="admin-scroll">
              <UTable
                v-if="!loading"
                :rows="tenantTableRows"
                :columns="tenantTableColumns"
                @select="selectTenant"
              />

              <USkeleton v-else class="h-80" />
            </div>
          </UCard>

          <UCard class="admin-card xl:col-span-2">
            <div v-if="tenantForm" class="admin-scroll space-y-6">
              <div class="flex items-start justify-between gap-4">
                <div>
                  <h2 class="text-lg font-semibold">{{ tenantForm.name }}</h2>
                  <p class="text-sm text-gray-500">Tenant-ID {{ tenantForm.id }}</p>
                </div>

                <UButton
                  color="primary"
                  :loading="savingTenant"
                  @click="saveTenant"
                >
                  Tenant speichern
                </UButton>
              </div>

              <UForm :state="tenantForm" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <UFormGroup label="Name">
                  <UInput v-model="tenantForm.name" />
                </UFormGroup>

                <UFormGroup label="Kürzel">
                  <UInput v-model="tenantForm.short" />
                </UFormGroup>
              </UForm>

              <div>
                <UDivider label="Zugeordnete Benutzer" class="mb-4" />
                <div class="flex flex-wrap gap-2">
                  <UBadge
                    v-for="user in getUsersForTenant(tenantForm.id)"
                    :key="`${tenantForm.id}-${user.id}`"
                    :color="user.is_admin ? 'primary' : 'gray'"
                    variant="subtle"
                  >
                    {{ user.display_name }}
                  </UBadge>
                </div>
              </div>
            </div>

            <UAlert
              v-else-if="!loading"
              title="Kein Tenant ausgewählt"
              description="Wähle links einen Tenant aus, um ihn zu bearbeiten."
              color="gray"
              variant="soft"
            />

            <div v-else class="admin-scroll">
              <USkeleton class="h-80" />
            </div>
          </UCard>
        </div>
      </template>
    </UTabs>
  </UDashboardPanelContent>

  <UModal v-model="createUserModalOpen">
    <UCard>
      <template #header>
        <div class="text-lg font-semibold">Benutzer anlegen</div>
      </template>

      <UForm
        :state="createUserForm"
        class="space-y-4"
        @submit.prevent="createUser"
      >
        <UFormGroup label="E-Mail">
          <UInput v-model="createUserForm.email" type="email" />
        </UFormGroup>

        <UFormGroup label="Initialpasswort">
          <UInput
            v-model="createUserForm.password"
            type="text"
            placeholder="Leer lassen für automatisches Passwort"
          />
        </UFormGroup>

        <UFormGroup label="Vorname für neues Profil">
          <UInput v-model="createUserForm.first_name" />
        </UFormGroup>

        <UFormGroup label="Nachname für neues Profil">
          <UInput v-model="createUserForm.last_name" />
        </UFormGroup>

        <UFormGroup label="Administrative Freigabe">
          <div class="flex items-center gap-3 h-10">
            <UToggle v-model="createUserForm.is_admin" />
            <span class="text-sm text-gray-600">Benutzer darf die Administration öffnen</span>
          </div>
        </UFormGroup>

        <UFormGroup label="Multi-Tenant">
          <div class="flex items-center gap-3 h-10">
            <UToggle v-model="createUserForm.multiTenant" />
            <span class="text-sm text-gray-600">Mehrere Tenant-Zuordnungen erlauben</span>
          </div>
        </UFormGroup>

        <div class="flex justify-end gap-3 pt-2">
          <UButton color="gray" variant="soft" @click="createUserModalOpen = false">
            Abbrechen
          </UButton>
          <UButton type="submit" color="primary" :loading="creatingUser">
            Benutzer anlegen
          </UButton>
        </div>
      </UForm>
    </UCard>
  </UModal>

  <UModal v-model="createTenantModalOpen">
    <UCard>
      <template #header>
        <div class="text-lg font-semibold">Tenant anlegen</div>
      </template>

      <UForm
        :state="createTenantForm"
        class="space-y-4"
        @submit.prevent="createTenant"
      >
        <UFormGroup label="Name">
          <UInput v-model="createTenantForm.name" />
        </UFormGroup>

        <UFormGroup label="Kürzel">
          <UInput v-model="createTenantForm.short" />
        </UFormGroup>

        <UAlert
          title="Seed-Daten"
          description="Beim Anlegen werden Standard-Datei-Tags und Systemordner für Dokumente und Eingangsbelege erzeugt."
          color="primary"
          variant="soft"
        />

        <div class="flex justify-end gap-3 pt-2">
          <UButton color="gray" variant="soft" @click="createTenantModalOpen = false">
            Abbrechen
          </UButton>
          <UButton type="submit" color="primary" :loading="creatingTenant">
            Tenant anlegen
          </UButton>
        </div>
      </UForm>
    </UCard>
  </UModal>

  <div class="mx-5 mb-5">
    <UAlert
      v-if="createdUserPassword"
      title="Initialpasswort für neuen Benutzer"
      :description="createdUserPassword"
      color="amber"
      variant="soft"
      close-button
      @close="createdUserPassword = ''"
    />
  </div>
</template>

<style scoped>
.admin-tabs :deep(.tabs-content) {
  height: 100%;
  min-height: 0;
}

.admin-tabs :deep(.tab-pane) {
  height: 100%;
  min-height: 0;
}

.admin-grid {
  height: calc(100vh - 13rem);
  min-height: 0;
}

.admin-card {
  height: 100%;
  min-height: 0;
}

.admin-card :deep(.divide-y) {
  height: 100%;
}

.admin-card :deep(.px-4.py-5.sm\:p-6) {
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.admin-scroll {
  min-height: 0;
  flex: 1;
  overflow-y: auto;
}
</style>
