"use client"

import { useMemo, useState } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getPaginationRowModel,
  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 { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar"
import { EmptyState } from "@/components/empty-state"
import { InboxIcon } from "lucide-react"

export interface Column<T> {
  key: string
  label: string
  render: (row: T) => React.ReactNode
  enableSorting?: boolean
}

interface DataTableProps<T extends { id: string }> {
  data: T[]
  columns: Column<T>[]
  searchPlaceholder?: string
  searchKeys?: (keyof T)[]
  isLoading?: boolean
  emptyTitle?: string
  emptyDescription?: string
  pagination?: boolean
  countLabel?: string
}

export function DataTable<T extends { id: string }>({
  data,
  columns,
  searchPlaceholder = "Поиск…",
  searchKeys = [],
  isLoading = false,
  emptyTitle = "Нет записей",
  emptyDescription,
  pagination = false,
  countLabel,
}: DataTableProps<T>) {
  const [search, setSearch] = useState("")

  const filteredData = useMemo(() => {
    if (!search || searchKeys.length === 0) return data
    const s = search.toLowerCase()
    return data.filter((row) =>
      searchKeys.some((k) => String(row[k]).toLowerCase().includes(s)),
    )
  }, [data, search, searchKeys])

  const columnDefs = useMemo<ColumnDef<T>[]>(
    () => {
      const defs: ColumnDef<T>[] = columns.map((col, index) => ({
        id: col.key,
        accessorKey: col.key,
        header: ({ column }) => (
          <DataGridSortHeader column={column} title={col.label} />
        ),
        cell: ({ row }) => col.render(row.original),
        enableSorting: col.enableSorting !== false,
        meta: {
          headerTitle: col.label,
          headerClassName:
            index === 0
              ? DATA_GRID_CELL_PAD_FIRST
              : index === columns.length - 1
                ? DATA_GRID_CELL_PAD_LAST
                : DATA_GRID_CELL_PAD,
          cellClassName:
            index === 0
              ? DATA_GRID_CELL_PAD_FIRST
              : index === columns.length - 1
                ? DATA_GRID_CELL_PAD_LAST
                : DATA_GRID_CELL_PAD,
        },
      }))
      return defs
    },
    [columns],
  )

  const table = useReactTable({
    data: filteredData,
    columns: columnDefs,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    ...(pagination ? { getPaginationRowModel: getPaginationRowModel() } : {}),
    getRowId: (row) => row.id,
  })

  const displayCount = searchKeys.length > 0 ? filteredData.length : data.length

  return (
    <DataPageCard>
      <DataPageToolbar
        search={search}
        onSearchChange={setSearch}
        searchPlaceholder={searchPlaceholder}
        countLabel={countLabel ?? `${displayCount} записей`}
      />
      <DataGridShell
        table={table}
        recordCount={filteredData.length}
        isLoading={isLoading}
        loadingMode="skeleton"
        pagination={pagination}
        emptyMessage={
          <EmptyState
            icon={<InboxIcon className="size-4" />}
            title={emptyTitle}
            description={emptyDescription}
            className="border-0 py-12"
          />
        }
      />
    </DataPageCard>
  )
}
