"use client";

import dynamic from "next/dynamic";
import { useMemo } from "react";
import type { ColDef, GridOptions } from "ag-grid-community";
import { AllCommunityModule, ModuleRegistry, themeQuartz } from "ag-grid-community";
import { AllEnterpriseModule } from "ag-grid-enterprise";

// Register the enterprise feature set once (community is included). Pure metadata,
// safe during SSR. The license key is applied separately (see AppChrome).
ModuleRegistry.registerModules([AllCommunityModule, AllEnterpriseModule]);

// AgGridReact touches the DOM, so load it client-only to keep SSR/route checks happy.
const AgGridReact = dynamic(() => import("ag-grid-react").then((m) => m.AgGridReact), {
  ssr: false,
  loading: () => <div className="py-8 text-center text-sm text-slate-400">Loading table…</div>,
}) as any;

// A lightly tuned Quartz theme matching the app's brand accent.
const theme = themeQuartz.withParams({
  accentColor: "#1d4ed8",
  fontFamily: "inherit",
  headerFontWeight: 600,
  borderRadius: 8,
  wrapperBorderRadius: 8,
});

export type { ColDef } from "ag-grid-community";

type DataGridProps = {
  rowData: unknown[];
  columnDefs: ColDef[];
  /** Fixed pixel/CSS height (default 440). Ignored when autoHeight is set. */
  height?: number | string;
  /** Size the grid to its content instead of a fixed height (use for short tables). */
  autoHeight?: boolean;
} & Partial<GridOptions> &
  Record<string, unknown>;

export function DataGrid({ rowData, columnDefs, height = 440, autoHeight = false, ...rest }: DataGridProps) {
  const defaultColDef = useMemo<ColDef>(
    () => ({ sortable: true, resizable: true, filter: true, flex: 1, minWidth: 90 }),
    [],
  );

  return (
    <div style={autoHeight ? { width: "100%" } : { height, width: "100%" }}>
      <AgGridReact
        theme={theme}
        rowData={rowData}
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        domLayout={autoHeight ? "autoHeight" : "normal"}
        animateRows
        suppressCellFocus
        {...rest}
      />
    </div>
  );
}
