"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { Asn } from "@/lib/data"
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 { FilterIcon, NetworkIcon } from "lucide-react"

interface AsnsDataGridProps {
  asns: Asn[]
  isLoading?: boolean
  pagination?: boolean
}

function AsnsDataGrid({ asns, isLoading, pagination = false }: AsnsDataGridProps) {
  const columns = useMemo<ColumnDef<Asn>[]>(
    () => [
      {
        id: "asn",
        accessorKey: "asn",
        header: ({ column }) => <DataGridSortHeader column={column} title="ASN" className="ml-1" />,
        cell: ({ row }) => <span className="font-mono font-semibold">{row.original.asn}</span>,
        meta: {
          headerTitle: "ASN",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "org",
        accessorKey: "org",
        header: ({ column }) => <DataGridSortHeader column={column} title="Имя / организация" />,
        cell: ({ row }) => (
          <span className="font-medium max-w-[min(28rem,50vw)] truncate block" title={row.original.org}>
            {row.original.org}
          </span>
        ),
        meta: {
          headerTitle: "Имя / организация",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "prefixes",
        accessorKey: "prefixes",
        header: ({ column }) => <DataGridSortHeader column={column} title="Префиксов" />,
        cell: ({ row }) => (
          <span className="font-mono tabular-nums">{row.original.prefixes.toLocaleString("ru")}</span>
        ),
        meta: {
          headerTitle: "Префиксов",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "filter",
        accessorKey: "filter",
        header: ({ column }) => <DataGridSortHeader column={column} title="Фильтр" />,
        cell: ({ row }) => (
          <span className="inline-flex items-center gap-1 text-xs bg-muted rounded px-2 py-0.5">
            <FilterIcon className="size-3 text-muted-foreground" />
            {row.original.filter}
          </span>
        ),
        meta: {
          headerTitle: "Фильтр",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "updated",
        accessorKey: "updated",
        header: ({ column }) => <DataGridSortHeader column={column} title="Обновлён" />,
        cell: ({ row }) => <span className="text-xs text-muted-foreground">{row.original.updated}</span>,
        meta: {
          headerTitle: "Обновлён",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "enabled",
        accessorKey: "enabled",
        header: ({ column }) => <DataGridSortHeader column={column} title="Статус" />,
        cell: ({ row }) => (
          <span
            className={`text-xs font-medium ${row.original.enabled ? "text-emerald-600" : "text-muted-foreground"}`}
          >
            {row.original.enabled ? "Активен" : "Отключён"}
          </span>
        ),
        meta: {
          headerTitle: "Статус",
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [],
  )

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

  return (
    <DataGridShell
      table={table}
      recordCount={asns.length}
      isLoading={isLoading}
      loadingMode="skeleton"
      pagination={pagination}
      emptyMessage={
        <EmptyState
          icon={<NetworkIcon className="size-4" />}
          title="Нет ASN"
          description="Добавьте автономные системы или импортируйте каталог"
          className="border-0 py-12"
        />
      }
    />
  )
}

export { AsnsDataGrid, type AsnsDataGridProps }
