'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { permissionAuditLogsQueryOptions } from '../api/queries';
import { permissionAuditLogColumns } from './permission-audit-log-columns';

const columnIds = permissionAuditLogColumns.map((column) => column.id).filter(Boolean) as string[];

export function PermissionAuditLogTable() {
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    search: parseAsString,
    user: parseAsString,
    action: parseAsString,
    dateFrom: parseAsString,
    dateTo: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.search && { search: params.search }),
    ...(params.user && { user: params.user }),
    ...(params.action && { action: params.action }),
    ...(params.dateFrom && { dateFrom: params.dateFrom }),
    ...(params.dateTo && { dateTo: params.dateTo }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };

  const { data } = useSuspenseQuery(permissionAuditLogsQueryOptions(filters));
  const pageCount = Math.max(1, Math.ceil(data.total_permission_audit_logs / params.perPage));

  const { table } = useDataTable({
    data: data.permission_audit_logs,
    columns: permissionAuditLogColumns,
    pageCount,
    shallow: true,
    debounceMs: 300
  });

  return (
    <DataTable table={table}>
      <DataTableToolbar table={table} />
    </DataTable>
  );
}
