"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 { ActivityIcon } from "lucide-react"

export interface BfdSessionRow {
  id: string
  serverId: string
  serverLabel: string
  localAddr: string
  remoteAddr: string
  state: "Up" | "Down" | "Init" | "AdminDown"
  interval: number
  multiplier: number
  iface: string
  uptime: string | null
  multihop: boolean
  rxInterval: number
  holdTime: number
  packetsRx: number
  packetsTx: number
  stateChanges: number
}

function stateClass(state: BfdSessionRow["state"]) {
  if (state === "Up")
    return "bg-[var(--status-online-bg)] text-[var(--status-online-fg)] border-current/25"
  if (state === "Init")
    return "bg-[var(--status-degraded-bg)] text-[var(--status-degraded-fg)] border-current/25"
  return "bg-[var(--status-offline-bg)] text-[var(--status-offline-fg)] border-current/25"
}

function Chip({ children, color }: { children: React.ReactNode; color?: string }) {
  return (
    <span
      className={cn(
        "inline-flex items-center rounded px-1.5 py-0.5 text-[11px] font-medium border",
        color ?? "bg-muted text-muted-foreground border-border",
      )}
    >
      {children}
    </span>
  )
}

function fmtMs(ms: number) {
  if (!ms) return "—"
  if (ms < 1000) return `${ms}ms`
  return `${(ms / 1000).toFixed(1)}s`
}

interface OspfBfdDataGridProps {
  sessions: BfdSessionRow[]
}

function OspfBfdDataGrid({ sessions }: OspfBfdDataGridProps) {
  const columns = useMemo<ColumnDef<BfdSessionRow>[]>(
    () => [
      {
        id: "serverLabel",
        accessorKey: "serverLabel",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Роутер" className="ml-1" />
        ),
        cell: ({ row }) => {
          const b = row.original
          return (
            <div className="flex flex-col gap-0.5">
              <span className="font-mono whitespace-nowrap">{b.serverLabel}</span>
              {b.multihop && (
                <Chip color="bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20">
                  multihop
                </Chip>
              )}
            </div>
          )
        },
        meta: {
          headerTitle: "Роутер",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "iface",
        accessorKey: "iface",
        header: ({ column }) => <DataGridSortHeader column={column} title="Интерфейс" />,
        cell: ({ row }) => (
          <span className="font-mono text-muted-foreground whitespace-nowrap">
            {row.original.iface || "—"}
          </span>
        ),
        meta: {
          headerTitle: "Интерфейс",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "localAddr",
        accessorKey: "localAddr",
        header: ({ column }) => <DataGridSortHeader column={column} title="Локальный" />,
        cell: ({ row }) => (
          <span className="font-mono whitespace-nowrap">{row.original.localAddr}</span>
        ),
        meta: {
          headerTitle: "Локальный",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "remoteAddr",
        accessorKey: "remoteAddr",
        header: ({ column }) => <DataGridSortHeader column={column} title="Удалённый" />,
        cell: ({ row }) => (
          <span className="font-mono whitespace-nowrap">{row.original.remoteAddr}</span>
        ),
        meta: {
          headerTitle: "Удалённый",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "state",
        accessorKey: "state",
        header: ({ column }) => <DataGridSortHeader column={column} title="Состояние" />,
        cell: ({ row }) => (
          <span
            className={cn(
              "inline-flex items-center rounded border px-1.5 py-0.5 text-[11px] font-medium",
              stateClass(row.original.state),
            )}
          >
            {row.original.state}
          </span>
        ),
        meta: {
          headerTitle: "Состояние",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "uptime",
        accessorKey: "uptime",
        header: ({ column }) => <DataGridSortHeader column={column} title="Uptime" />,
        cell: ({ row }) => (
          <span className="text-muted-foreground whitespace-nowrap tabular-nums">
            {row.original.uptime ?? "—"}
          </span>
        ),
        meta: {
          headerTitle: "Uptime",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "intervals",
        header: () => <span className="text-xs font-medium text-muted-foreground">Tx / Rx</span>,
        enableSorting: false,
        cell: ({ row }) => {
          const b = row.original
          return (
            <span className="font-mono tabular-nums text-muted-foreground whitespace-nowrap">
              {fmtMs(b.interval)} / {fmtMs(b.rxInterval)}
            </span>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "holdTime",
        accessorKey: "holdTime",
        header: ({ column }) => <DataGridSortHeader column={column} title="Hold" />,
        cell: ({ row }) => (
          <span className="font-mono tabular-nums text-muted-foreground whitespace-nowrap">
            {fmtMs(row.original.holdTime)}
          </span>
        ),
        meta: {
          headerTitle: "Hold",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "multiplier",
        accessorKey: "multiplier",
        header: ({ column }) => <DataGridSortHeader column={column} title="Mult" />,
        cell: ({ row }) => (
          <span className="font-mono tabular-nums text-center block">{row.original.multiplier}</span>
        ),
        meta: {
          headerTitle: "Mult",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
        },
      },
      {
        id: "packetsRx",
        accessorKey: "packetsRx",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Пакеты Rx" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <span className="font-mono tabular-nums text-right text-muted-foreground block">
            {row.original.packetsRx.toLocaleString()}
          </span>
        ),
        meta: {
          headerTitle: "Пакеты Rx",
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "packetsTx",
        accessorKey: "packetsTx",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Пакеты Tx" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <span className="font-mono tabular-nums text-right text-muted-foreground block">
            {row.original.packetsTx.toLocaleString()}
          </span>
        ),
        meta: {
          headerTitle: "Пакеты Tx",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "stateChanges",
        accessorKey: "stateChanges",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Переходы" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <span className="font-mono tabular-nums text-right block">{row.original.stateChanges}</span>
        ),
        meta: {
          headerTitle: "Переходы",
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: cn(DATA_GRID_CELL_PAD_LAST, "text-right"),
        },
      },
    ],
    [],
  )

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

  if (sessions.length === 0) {
    return (
      <EmptyState
        icon={<ActivityIcon className="size-4" />}
        title="BFD-сессий не обнаружено"
        className="border-0 py-10"
      />
    )
  }

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

export { OspfBfdDataGrid, type OspfBfdDataGridProps }
