"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getExpandedRowModel,
  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,
} 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 { BgpSessionDetail } from "@/components/data-grids/bgp-session-detail"
import type { BgpSessionRow, BgpState, BgpType } from "@/lib/bgp/types"
import { BGP_AS_NAMES } from "@/lib/bgp/types"
import { fmtBgpNum } from "@/lib/bgp/helpers"
import { ChevronDownIcon, ChevronRightIcon, NetworkIcon } from "lucide-react"

const STATE_STYLE: Record<BgpState, { bg: string; text: string; dot: string; label: string }> = {
  Established: {
    bg: "bg-emerald-500/10",
    text: "text-emerald-600 dark:text-emerald-400",
    dot: "bg-emerald-500",
    label: "Established",
  },
  Active: {
    bg: "bg-amber-500/10",
    text: "text-amber-600 dark:text-amber-400",
    dot: "bg-amber-500",
    label: "Active",
  },
  Idle: {
    bg: "bg-slate-500/10",
    text: "text-slate-500 dark:text-slate-400",
    dot: "bg-slate-500",
    label: "Idle",
  },
  Connect: {
    bg: "bg-blue-500/10",
    text: "text-blue-600 dark:text-blue-400",
    dot: "bg-blue-500",
    label: "Connect",
  },
  OpenSent: {
    bg: "bg-violet-500/10",
    text: "text-violet-600 dark:text-violet-400",
    dot: "bg-violet-500",
    label: "OpenSent",
  },
  OpenConfirm: {
    bg: "bg-violet-500/10",
    text: "text-violet-600 dark:text-violet-400",
    dot: "bg-violet-500",
    label: "OpenConfirm",
  },
}

const TYPE_STYLE: Record<BgpType, { bg: string; text: string }> = {
  eBGP: { bg: "bg-blue-500/10", text: "text-blue-600 dark:text-blue-400" },
  iBGP: { bg: "bg-purple-500/10", text: "text-purple-600 dark:text-purple-400" },
}

function StateBadge({ state }: { state: BgpState }) {
  const s = STATE_STYLE[state]
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 rounded border px-2 py-0.5 text-[11px] font-semibold",
        s.bg,
        s.text,
        "border-current/20",
      )}
    >
      <span className={cn("size-1.5 rounded-full shrink-0", s.dot)} />
      {s.label}
    </span>
  )
}

function TypeBadge({ type }: { type: BgpType }) {
  const s = TYPE_STYLE[type]
  return (
    <span
      className={cn(
        "inline-flex items-center rounded border px-1.5 py-0.5 text-[10px] font-semibold",
        s.bg,
        s.text,
        "border-current/20",
      )}
    >
      {type}
    </span>
  )
}

interface BgpSessionsDataGridProps {
  sessions: BgpSessionRow[]
}

function BgpSessionsDataGrid({ sessions }: BgpSessionsDataGridProps) {
  const columns = useMemo<ColumnDef<BgpSessionRow>[]>(
    () => [
      {
        id: "serverLabel",
        accessorKey: "serverLabel",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Роутер" className="ml-1" />
        ),
        cell: ({ row }) => {
          const expanded = row.getIsExpanded()
          return (
            <div className="flex items-center gap-2">
              {expanded ? (
                <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
              ) : (
                <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground/40" />
              )}
              <span className="font-mono whitespace-nowrap">{row.original.serverLabel}</span>
            </div>
          )
        },
        meta: {
          headerTitle: "Роутер",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
          expandedContent: (row: BgpSessionRow) => <BgpSessionDetail session={row} />,
        },
      },
      {
        id: "peerIp",
        accessorKey: "peerIp",
        header: ({ column }) => <DataGridSortHeader column={column} title="Peer IP" />,
        cell: ({ row }) => <span className="font-mono">{row.original.peerIp}</span>,
        meta: {
          headerTitle: "Peer IP",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "remoteAs",
        accessorKey: "remoteAs",
        header: ({ column }) => <DataGridSortHeader column={column} title="Remote AS" />,
        cell: ({ row }) => {
          const as = row.original.remoteAs
          return (
            <div className="flex items-center gap-1.5 font-mono">
              <span>AS{as}</span>
              {BGP_AS_NAMES[as] && (
                <span className="text-muted-foreground text-[10px]">{BGP_AS_NAMES[as]}</span>
              )}
            </div>
          )
        },
        meta: {
          headerTitle: "Remote AS",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "description",
        accessorKey: "description",
        header: ({ column }) => <DataGridSortHeader column={column} title="Описание" />,
        cell: ({ row }) => (
          <span className="text-muted-foreground max-w-[180px] truncate block">
            {row.original.description}
          </span>
        ),
        meta: {
          headerTitle: "Описание",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "type",
        accessorKey: "type",
        header: ({ column }) => <DataGridSortHeader column={column} title="Тип" />,
        cell: ({ row }) => <TypeBadge type={row.original.type} />,
        meta: {
          headerTitle: "Тип",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "state",
        accessorKey: "state",
        header: ({ column }) => <DataGridSortHeader column={column} title="Состояние" />,
        cell: ({ row }) => <StateBadge state={row.original.state} />,
        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="font-mono tabular-nums text-muted-foreground">
            {row.original.uptime ?? "—"}
          </span>
        ),
        meta: {
          headerTitle: "Uptime",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "prefixesRx",
        accessorKey: "prefixesRx",
        header: ({ column }) => <DataGridSortHeader column={column} title="Prefixes ↓" />,
        cell: ({ row }) => {
          const n = row.original.prefixesRx
          return n > 0 ? (
            <span className="font-mono tabular-nums text-emerald-600 dark:text-emerald-400 text-right block">
              {fmtBgpNum(n)}
            </span>
          ) : (
            <span className="text-muted-foreground">—</span>
          )
        },
        meta: {
          headerTitle: "Prefixes ↓",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "prefixesTx",
        accessorKey: "prefixesTx",
        header: ({ column }) => <DataGridSortHeader column={column} title="Prefixes ↑" />,
        cell: ({ row }) => {
          const n = row.original.prefixesTx
          return n > 0 ? (
            <span className="font-mono tabular-nums text-[var(--chart-tx)] text-right block">
              {fmtBgpNum(n)}
            </span>
          ) : (
            <span className="text-muted-foreground">—</span>
          )
        },
        meta: {
          headerTitle: "Prefixes ↑",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
    ],
    [],
  )

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

  if (sessions.length === 0) {
    return (
      <EmptyState
        icon={<NetworkIcon className="size-4" />}
        title="Нет BGP-сессий"
        description="Измените фильтры или проверьте подключение к роутерам"
        className="border-0 py-10"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={sessions.length}
      onRowClick={(row) => table.getRow(row.id).toggleExpanded()}
    />
  )
}

export { BgpSessionsDataGrid, type BgpSessionsDataGridProps }
