"use client"

import { useMemo, type ReactNode } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { WireGuardPeer } from "@/lib/data"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
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 { fmtBytes, truncKey } from "@/components/data-grids/wireguard-peers-detail"
import {
  ArrowDownIcon,
  ArrowUpIcon,
  CodeXmlIcon,
  KeyRoundIcon,
  Trash2Icon,
  UsersIcon,
} from "lucide-react"

export interface WgPeerRow extends WireGuardPeer {
  id: string
  ifaceId: string
  ifaceName: string
  serverId: string
  serverName: string
  serverCountry: string
}

interface WireguardPeersGridProps {
  peers: WgPeerRow[]
  compactServer?: boolean
  emptyAction?: ReactNode
  onDeletePeer?: (row: WgPeerRow) => void
  onExportPeer?: (row: WgPeerRow) => void
}

function WireguardPeersGrid({
  peers,
  compactServer = false,
  emptyAction,
  onDeletePeer,
  onExportPeer,
}: WireguardPeersGridProps) {
  const columns = useMemo<ColumnDef<WgPeerRow>[]>(() => {
    const cols: ColumnDef<WgPeerRow>[] = [
      {
        id: "peer",
        accessorKey: "publicKey",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Пир" className="ml-1" />
        ),
        cell: ({ row }) => {
          const peer = row.original
          return (
            <div className="flex min-w-0 items-center gap-1.5">
              <KeyRoundIcon className="size-3.5 shrink-0 text-muted-foreground" />
              <span className="truncate font-mono text-xs" title={peer.publicKey}>
                {peer.name || truncKey(peer.publicKey)}
              </span>
            </div>
          )
        },
        meta: {
          headerTitle: "Пир",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "iface",
        accessorKey: "ifaceName",
        header: ({ column }) => <DataGridSortHeader column={column} title="Интерфейс" />,
        cell: ({ row }) => (
          <span className="font-mono text-sm">{row.original.ifaceName}</span>
        ),
        meta: {
          headerTitle: "Интерфейс",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
    ]

    if (!compactServer) {
      cols.push({
        id: "server",
        accessorKey: "serverName",
        header: ({ column }) => <DataGridSortHeader column={column} title="Сервер" />,
        cell: ({ row }) => (
          <div className="flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground">
            <Flag code={row.original.serverCountry || "UN"} size={12} />
            {row.original.serverName}
          </div>
        ),
        meta: {
          headerTitle: "Сервер",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      })
    }

    cols.push(
      {
        id: "allowedIps",
        accessorFn: (row) => row.allowedIps.join(", "),
        header: ({ column }) => <DataGridSortHeader column={column} title="Allowed IPs" />,
        cell: ({ row }) => (
          <span className="block truncate font-mono text-xs text-muted-foreground">
            {row.original.allowedIps.join(", ") || "—"}
          </span>
        ),
        meta: {
          headerTitle: "Allowed IPs",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "handshake",
        accessorKey: "latestHandshake",
        header: ({ column }) => <DataGridSortHeader column={column} title="Handshake" />,
        cell: ({ row }) => (
          <span
            className={cn(
              "whitespace-nowrap font-mono text-[11px]",
              row.original.latestHandshake ? "text-success" : "text-muted-foreground",
            )}
          >
            {row.original.latestHandshake ?? "нет рукопожатия"}
          </span>
        ),
        meta: {
          headerTitle: "Handshake",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "transfer",
        header: () => (
          <span className="text-xs font-medium text-muted-foreground">RX / TX</span>
        ),
        enableSorting: false,
        cell: ({ row }) => (
          <div className="flex items-center gap-2 whitespace-nowrap text-xs text-muted-foreground">
            <span className="flex items-center gap-0.5">
              <ArrowDownIcon className="size-3 text-success" />
              {fmtBytes(row.original.transferRx)}
            </span>
            <span className="flex items-center gap-0.5">
              <ArrowUpIcon className="size-3 text-info" />
              {fmtBytes(row.original.transferTx)}
            </span>
          </div>
        ),
        meta: {
          headerTitle: "RX / TX",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "endpoint",
        accessorKey: "endpoint",
        header: ({ column }) => <DataGridSortHeader column={column} title="Endpoint" />,
        cell: ({ row }) => (
          <span className="font-mono text-[11px] text-muted-foreground">
            {row.original.endpoint ?? "—"}
          </span>
        ),
        meta: {
          headerTitle: "Endpoint",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        enableSorting: false,
        size: 72,
        cell: ({ row }) => {
          const peer = row.original
          return (
            <div className="flex justify-end gap-0.5">
              {onExportPeer ? (
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="size-7"
                  aria-label="Экспорт peer .conf"
                  onClick={() => onExportPeer(peer)}
                >
                  <CodeXmlIcon className="size-3.5" />
                </Button>
              ) : null}
              {onDeletePeer ? (
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="size-7 text-destructive"
                  aria-label="Удалить пира"
                  onClick={() => onDeletePeer(peer)}
                >
                  <Trash2Icon className="size-3.5" />
                </Button>
              ) : null}
            </div>
          )
        },
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    )

    return cols
  }, [compactServer, onDeletePeer, onExportPeer])

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

  if (peers.length === 0) {
    return (
      <EmptyState
        icon={<UsersIcon className="size-4" />}
        title="Нет пиров"
        description="Добавьте пира к интерфейсу или сбросьте поиск"
        action={emptyAction}
        className="border-0 py-16"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={peers.length}
      tableClassNames={{
        headerRow: "border-b border-border",
        bodyRow: cn("group/row"),
      }}
    />
  )
}

export { WireguardPeersGrid, type WireguardPeersGridProps }
