"use client"

import { useRouter, useSearchParams } from "next/navigation"
import { Suspense } from "react"
import { AuditLogTable } from "./audit-log-table"
import { AuditLogFilters } from "./audit-log-filters"
import type { AuditLog } from "../types"

interface AuditLogViewProps {
  items: AuditLog[]
  page: number
  pageSize: number
  total: number
  totalPages: number
  moduleOptions: string[]
}

function AuditLogViewInner({
  items,
  page,
  pageSize,
  total,
  totalPages,
  moduleOptions,
}: AuditLogViewProps) {
  const router = useRouter()
  const searchParams = useSearchParams()

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString())
    if (newPage <= 1) {
      params.delete("page")
    } else {
      params.set("page", String(newPage))
    }
    const query = params.toString()
    router.push(query ? `?${query}` : "?")
  }

  return (
    <div className="space-y-4">
      <AuditLogFilters moduleOptions={moduleOptions} />
      <AuditLogTable
        items={items}
        page={page}
        pageSize={pageSize}
        total={total}
        totalPages={totalPages}
        onPageChange={handlePageChange}
      />
    </div>
  )
}

export function AuditLogView(props: AuditLogViewProps) {
  return (
    <Suspense fallback={null}>
      <AuditLogViewInner {...props} />
    </Suspense>
  )
}
