"use client"

import { useMemo, type ReactNode } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getExpandedRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
  DATA_GRID_CELL_PAD,
  DATA_GRID_CELL_PAD_FIRST,
  DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import { EmptyState } from "@/components/empty-state"
import { InboxIcon } from "lucide-react"

export interface CompactDataGridColumn<T> {
  id: string
  header: string
  accessorKey?: keyof T & string
  cell?: (row: T) => ReactNode
  enableSorting?: boolean
  headerClassName?: string
  cellClassName?: string
}

interface CompactDataGridProps<T extends { id: string }> {
  data: T[]
  columns: CompactDataGridColumn<T>[]
  isLoading?: boolean
  emptyTitle?: string
  emptyDescription?: string
  onRowClick?: (row: T) => void
  getExpandedContent?: (row: T) => ReactNode
}

function CompactDataGrid<T extends { id: string }>({
  data,
  columns,
  isLoading,
  emptyTitle = "Нет записей",
  emptyDescription,
  onRowClick,
  getExpandedContent,
}: CompactDataGridProps<T>) {
  const columnDefs = useMemo<ColumnDef<T>[]>(
    () =>
      columns.map((col, index) => ({
        id: col.id,
        accessorKey: col.accessorKey ?? col.id,
        header: ({ column }) => (
          <DataGridSortHeader column={column} title={col.header} className={index === 0 ? "ml-1" : undefined} />
        ),
        cell: ({ row }) => (col.cell ? col.cell(row.original) : String(row.getValue(col.id) ?? "—")),
        enableSorting: col.enableSorting !== false,
        meta: {
          headerTitle: col.header,
          headerClassName:
            col.headerClassName ??
            (index === 0
              ? DATA_GRID_CELL_PAD_FIRST
              : index === columns.length - 1
                ? DATA_GRID_CELL_PAD_LAST
                : DATA_GRID_CELL_PAD),
          cellClassName:
            col.cellClassName ??
            (index === 0
              ? DATA_GRID_CELL_PAD_FIRST
              : index === columns.length - 1
                ? DATA_GRID_CELL_PAD_LAST
                : DATA_GRID_CELL_PAD),
          ...(getExpandedContent && index === 0
            ? { expandedContent: getExpandedContent }
            : {}),
        },
      })),
    [columns, getExpandedContent],
  )

  const table = useReactTable({
    data,
    columns: columnDefs,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    ...(getExpandedContent ? { getExpandedRowModel: getExpandedRowModel() } : {}),
    getRowId: (row) => row.id,
    ...(getExpandedContent ? { getRowCanExpand: () => true } : {}),
  })

  return (
    <DataGridShell
      table={table}
      recordCount={data.length}
      isLoading={isLoading}
      loadingMode="skeleton"
      onRowClick={
        onRowClick ??
        (getExpandedContent
          ? (row) => table.getRow(row.id).toggleExpanded()
          : undefined)
      }
      emptyMessage={
        <EmptyState
          icon={<InboxIcon className="size-4" />}
          title={emptyTitle}
          description={emptyDescription}
          className="border-0 py-10"
        />
      }
    />
  )
}

export { CompactDataGrid, type CompactDataGridProps }
