"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { Server, VxlanTunnel } from "@/lib/data"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
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 {
  CodeXmlIcon,
  MoreHorizontalIcon,
  NetworkIcon,
  PencilIcon,
  PowerIcon,
  Trash2Icon,
} from "lucide-react"

interface VxlanDataGridProps {
  tunnels: VxlanTunnel[]
  servers: Server[]
  onExport: (tunnel: VxlanTunnel) => void
}

function VxlanDataGrid({ tunnels, servers, onExport }: VxlanDataGridProps) {
  const serverMap = useMemo(
    () => new Map(servers.map((s) => [s.id, s])),
    [servers],
  )

  const columns = useMemo<ColumnDef<VxlanTunnel>[]>(
    () => [
      {
        id: "name",
        accessorKey: "name",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Имя / VTEP" className="ml-1" />
        ),
        cell: ({ row }) => {
          const t = row.original
          return (
            <div className="min-w-0 flex items-start gap-2">
              <span
                className={cn(
                  "size-2 rounded-full shrink-0 mt-1.5",
                  t.status === "up" ? "bg-emerald-500" : "bg-red-500",
                )}
              />
              <div className="min-w-0">
                <p className="font-mono font-medium text-sm truncate">{t.name}</p>
                <p className="text-[11px] text-muted-foreground font-mono">VTEP: {t.vtepIp}</p>
              </div>
            </div>
          )
        },
        meta: {
          headerTitle: "Имя / VTEP",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "server",
        accessorKey: "serverId",
        header: ({ column }) => <DataGridSortHeader column={column} title="Сервер" />,
        cell: ({ row }) => {
          const srv = serverMap.get(row.original.serverId)
          if (!srv) return <span className="text-muted-foreground">—</span>
          return (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground min-w-0">
              <Flag code={srv.country} size={12} />
              <span className="font-mono truncate">{srv.name}</span>
            </div>
          )
        },
        meta: {
          headerTitle: "Сервер",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "vni",
        accessorKey: "vni",
        header: ({ column }) => <DataGridSortHeader column={column} title="VNI" />,
        cell: ({ row }) => <span className="font-mono text-sm">{row.original.vni}</span>,
        meta: {
          headerTitle: "VNI",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
        },
      },
      {
        id: "dstPort",
        accessorKey: "dstPort",
        header: ({ column }) => <DataGridSortHeader column={column} title="Port" />,
        cell: ({ row }) => <span className="font-mono text-sm">{row.original.dstPort}</span>,
        meta: {
          headerTitle: "Port",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
        },
      },
      {
        id: "remoteVteps",
        header: () => (
          <span className="text-xs font-medium text-muted-foreground">Remote</span>
        ),
        enableSorting: false,
        cell: ({ row }) => (
          <span className="font-mono text-sm text-center block">{row.original.remoteVteps.length}</span>
        ),
        meta: {
          headerTitle: "Remote",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
        },
      },
      {
        id: "arpProxy",
        accessorKey: "arpProxy",
        header: () => <span className="sr-only">ARP</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span
            className={cn(
              "text-[10px] font-mono px-1.5 py-0.5 rounded",
              row.original.arpProxy
                ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
                : "bg-muted text-muted-foreground",
            )}
          >
            ARP {row.original.arpProxy ? "✓" : "✗"}
          </span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "macLearning",
        accessorKey: "macLearning",
        header: () => <span className="sr-only">MAC</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span
            className={cn(
              "text-[10px] font-mono px-1.5 py-0.5 rounded",
              row.original.macLearning
                ? "bg-sky-500/10 text-sky-600 dark:text-sky-400"
                : "bg-muted text-muted-foreground",
            )}
          >
            MAC {row.original.macLearning ? "✓" : "✗"}
          </span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "status",
        accessorKey: "status",
        header: ({ column }) => <DataGridSortHeader column={column} title="Статус" />,
        cell: ({ row }) => (
          <span
            className={cn(
              "text-[11px] font-mono px-2 py-0.5 rounded border whitespace-nowrap",
              row.original.status === "up"
                ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20"
                : "bg-red-500/10 text-red-500 border-red-500/20",
            )}
          >
            {row.original.status === "up" ? "UP" : "DOWN"}
          </span>
        ),
        meta: {
          headerTitle: "Статус",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        cell: ({ row }) => {
          const tunnel = row.original
          return (
            <div className="flex justify-end">
              <DropdownMenu>
                <DropdownMenuTrigger
                  render={
                    <Button
                      type="button"
                      variant="outline"
                      size="icon"
                      className={cn(
                        "size-8 shrink-0 border-border/60 bg-background/80 text-muted-foreground shadow-none",
                        "opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100",
                        "data-popup-open:opacity-100",
                      )}
                      aria-label={`Действия: ${tunnel.name}`}
                    >
                      <MoreHorizontalIcon className="size-4" />
                    </Button>
                  }
                />
                <DropdownMenuContent side="bottom" align="end">
                  <DropdownMenuItem onClick={() => onExport(tunnel)}>
                    <CodeXmlIcon className="size-4" />
                    Экспорт .rsc
                  </DropdownMenuItem>
                  <DropdownMenuItem>
                    <PencilIcon className="size-4" />
                    Редактировать
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem>
                    <PowerIcon className="size-4" />
                    {tunnel.enabled ? "Отключить" : "Включить"}
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem variant="destructive">
                    <Trash2Icon className="size-4" />
                    Удалить
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          )
        },
        enableSorting: false,
        size: 56,
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [onExport, serverMap],
  )

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

  if (tunnels.length === 0) {
    return (
      <EmptyState
        icon={<NetworkIcon className="size-4" />}
        title="Нет VXLAN-туннелей"
        description="Добавьте туннель или измените поиск"
        className="border-0 py-16"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={tunnels.length}
      tableClassNames={{
        headerRow: "border-b border-border",
        bodyRow: cn("group/row", "[&[data-disabled=true]]:opacity-50"),
      }}
    />
  )
}

export { VxlanDataGrid, type VxlanDataGridProps }
