<script setup lang="ts">
import { UserCog } from '@lucide/vue'

import AdminAuditDetailDrawer from '../../components/admin/AdminAuditDetailDrawer.vue'
import AdminAuditFocusPanel from '../../components/admin/AdminAuditFocusPanel.vue'
import AdminAuditLogList from '../../components/admin/AdminAuditLogList.vue'
import AdminAuditOverviewBar from '../../components/admin/AdminAuditOverviewBar.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import { watchAdminErrorToast } from '../../composables/useAdminToast'
import { useAdminAuditManager } from '../../components/admin/useAdminAuditManager'

const {
  query,
  selectedAdmin,
  selectedAction,
  entityFilter,
  fromDate,
  toDate,
  loadingAudit,
  loadingMore,
  auditError,
  exportMessage,
  selectedEntry,
  auditRows,
  adminCounts,
  actionCounts,
  entityCounts,
  logStats,
  focusCards,
  activeFilterCount,
  lastLoadedLabel,
  emptyStateText,
  pageSummaryLabel,
  hasMore,
  filterPresets,
  appliedPresetKey,
  entityOptions,
  loadAuditEntries,
  loadNextPage,
  exportAuditCsv,
  clearFilters,
  applyPreset,
  openAuditEntry,
  closeAuditEntry,
} = useAdminAuditManager()

watchAdminErrorToast(auditError)
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Audit-Log"
      description="Nachvollziehbare Admin-Aktionen mit Suche, Metadaten, Quick-Filtern und CSV-Export."
      :icon="UserCog"
    />

    <AdminAuditOverviewBar
      v-model:query="query"
      v-model:entity-filter="entityFilter"
      v-model:from-date="fromDate"
      v-model:to-date="toDate"
      :stats="logStats"
      :entity-options="entityOptions"
      :filter-presets="filterPresets"
      :applied-preset-key="appliedPresetKey"
      :export-message="exportMessage"
      :last-loaded-label="lastLoadedLabel"
      :loading="loadingAudit"
      :has-rows="auditRows.length > 0"
      :active-filter-count="activeFilterCount"
      @refresh="loadAuditEntries()"
      @export="exportAuditCsv"
      @clear="clearFilters"
      @apply-preset="applyPreset"
    />

    <section class="grid gap-6 2xl:grid-cols-[360px_minmax(0,1fr)]">
      <AdminAuditFocusPanel
        v-model:selected-admin="selectedAdmin"
        v-model:selected-action="selectedAction"
        v-model:selected-entity="entityFilter"
        :focus-cards="focusCards"
        :admin-counts="adminCounts"
        :action-counts="actionCounts"
        :entity-counts="entityCounts"
      />

      <AdminAuditLogList
        :entries="auditRows"
        :loading="loadingAudit"
        :loading-more="loadingMore"
        :has-more="hasMore"
        :page-summary-label="pageSummaryLabel"
        :empty-text="emptyStateText"
        @open-detail="openAuditEntry"
        @load-more="loadNextPage"
      />
    </section>

    <AdminAuditDetailDrawer :entry="selectedEntry" @close="closeAuditEntry" />
  </div>
</template>
