"use client"

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

export interface OspfPreviewInterfaceRow {
  id: string
  interface: string
  currentCost: number
  optimalCost: number
  score: number
  pingMs: number
  dlMbps: number
  ulMbps: number
}

interface RouteOptimizerOspfPreviewDataGridProps {
  rows: OspfPreviewInterfaceRow[]
  error?: string | null
  loading?: boolean
}

function RouteOptimizerOspfPreviewDataGrid({
  rows,
  error,
  loading,
}: RouteOptimizerOspfPreviewDataGridProps) {
  const columns = useMemo<ColumnDef<OspfPreviewInterfaceRow>[]>(
    () => [
      {
        id: "interface",
        accessorKey: "interface",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Интерфейс" className="ml-1" />
        ),
        cell: ({ row }) => <span className="font-mono">{row.original.interface}</span>,
        meta: {
          headerTitle: "Интерфейс",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "cost",
        accessorKey: "currentCost",
        header: ({ column }) => <DataGridSortHeader column={column} title="Cost" />,
        cell: ({ row }) => {
          const r = row.original
          return (
            <span className="font-mono">
              <span className="text-sky-600 dark:text-sky-400">{r.currentCost}</span>
              {" → "}
              <span
                className={
                  r.currentCost === r.optimalCost
                    ? "text-emerald-600 dark:text-emerald-400"
                    : "text-amber-600 dark:text-amber-400"
                }
              >
                {r.optimalCost}
              </span>
            </span>
          )
        },
        meta: { headerTitle: "Cost", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "score",
        accessorKey: "score",
        header: ({ column }) => <DataGridSortHeader column={column} title="Score" />,
        cell: ({ row }) => <span className="font-mono">{row.original.score}</span>,
        meta: { headerTitle: "Score", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "pingMs",
        accessorKey: "pingMs",
        header: ({ column }) => <DataGridSortHeader column={column} title="Ping" />,
        cell: ({ row }) => <span className="font-mono">{row.original.pingMs}ms</span>,
        meta: { headerTitle: "Ping", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "speed",
        header: () => <span className="text-xs font-medium text-muted-foreground">Speed (dl/ul)</span>,
        enableSorting: false,
        cell: ({ row }) => {
          const r = row.original
          return (
            <span className="font-mono">
              ↓{r.dlMbps} / ↑{r.ulMbps}
            </span>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD_LAST, cellClassName: DATA_GRID_CELL_PAD_LAST },
      },
    ],
    [],
  )

  const table = useReactTable({
    data: rows,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getRowId: (row) => row.id,
  })

  if (error) {
    return (
      <p className="px-3 py-2 text-xs text-destructive">Ошибка preview: {error}</p>
    )
  }

  if (!loading && rows.length === 0) {
    return (
      <EmptyState
        icon={<NetworkIcon className="size-4" />}
        title="Интерфейсы OSPF не найдены для выбранного сервера"
        className="border-0 py-6 text-xs"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={rows.length}
      isLoading={loading}
      loadingMode="skeleton"
      tableClassNames={{ headerRow: "border-b bg-muted/30", bodyRow: "group/row" }}
      tableLayout={{ dense: true }}
    />
  )
}

export { RouteOptimizerOspfPreviewDataGrid, type RouteOptimizerOspfPreviewDataGridProps }
