import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { listObjects } from "../api/service";
import { Notice } from "../components/StateBlock";
import {
  EMPTY_OBJECT_FILTERS,
  objectFiltersFromParams,
  objectFiltersToParams,
  ObjectsTable,
  type ObjectFilterValues,
} from "../components/ObjectsTable";
import { PageHeader } from "../components/PageHeader";
import { Panel } from "../components/Panel";
import { useRun } from "../lib/useRun";

export default function ObjectsPage() {
  const { runId } = useRun();
  const [searchParams, setSearchParams] = useSearchParams();
  const filters = useMemo(() => objectFiltersFromParams(searchParams), [searchParams]);

  const setFilters = (next: ObjectFilterValues) => {
    setSearchParams(objectFiltersToParams(next, searchParams), { preventScrollReset: true });
  };

  const hasFilters =
    filters.type !== EMPTY_OBJECT_FILTERS.type ||
    filters.result !== "" ||
    filters.reason !== "" ||
    filters.rejectedOnly ||
    filters.q !== "";

  return (
    <div className="page">
      <PageHeader
        title="Objects"
        subtitle="Browse every object instance indexed for the active run. Lists stream from the run report — deep paging on large runs can be slow."
      />
      {!hasFilters ? (
        <Notice kind="info">
          This run may contain hundreds of thousands of objects. Use the filters to
          narrow the scan; all filters are applied server-side.
        </Notice>
      ) : null}
      <Panel title="All objects" flush>
        <ObjectsTable
          runId={runId}
          queryKeyScope="global"
          fetcher={(f) => listObjects(runId, f)}
          filters={filters}
          onFiltersChange={setFilters}
        />
      </Panel>
    </div>
  );
}
