"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
  compact?: boolean
}

function CompactDataGrid<T extends { id: string }>({
  data,
  columns,
  isLoading,
  emptyTitle = "Нет записей",
  emptyDescription,
  onRowClick,
  getExpandedContent,
  compact = false,
}: CompactDataGridProps<T>) {
  const pad = compact ? "py-2" : DATA_GRID_CELL_PAD
  const padFirst = compact ? "pl-4 py-2" : DATA_GRID_CELL_PAD_FIRST
  const padLast = compact ? "pr-4 py-2" : DATA_GRID_CELL_PAD_LAST

  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 ? padFirst : index === columns.length - 1 ? padLast : pad),
          cellClassName:
            col.cellClassName ??
            (index === 0 ? padFirst : index === columns.length - 1 ? padLast : pad),
          ...(getExpandedContent && index === 0
            ? { expandedContent: getExpandedContent }
            : {}),
        },
      })),
    [columns, getExpandedContent, pad, padFirst, padLast],
  )

  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 }
