"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getExpandedRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { Server, ServerType } from "@/lib/data"
import { StatusBadge } from "@/components/status-badge"
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 { ServerExpandedDetail } from "@/components/data-grids/server-expanded-detail"
import {
  ChevronRightIcon,
  ChevronDownIcon,
  HomeIcon,
  ServerIcon,
  NetworkIcon,
  ShieldIcon,
  WifiIcon,
  MoreHorizontalIcon,
  ExternalLinkIcon,
  PencilIcon,
  RefreshCwIcon,
  PowerIcon,
  Trash2Icon,
} from "lucide-react"

const TYPE_LABELS: Record<ServerType, string> = {
  "jump-host": "JumpHost",
  "exit-node": "Exit Node",
  "home-router": "Home Router",
}

const TYPE_STYLES: Record<ServerType, string> = {
  "jump-host": "bg-violet-500/10 text-violet-400 border-violet-500/20",
  "exit-node": "bg-sky-500/10 text-sky-400 border-sky-500/20",
  "home-router": "bg-emerald-500/10 text-emerald-400 border-emerald-500/20",
}

function rosVer(os: string): number {
  const m = os.match(/(\d+)\.(\d+)/)
  if (!m) return 0
  return parseInt(m[1], 10) * 100 + parseInt(m[2], 10)
}

function TypeBadge({ type }: { type: ServerType }) {
  const icon =
    type === "jump-host" ? <ServerIcon className="size-3 mr-1" />
    : type === "exit-node" ? <NetworkIcon className="size-3 mr-1" />
    : <HomeIcon className="size-3 mr-1" />
  return (
    <span className={cn("inline-flex items-center text-xs font-medium border rounded px-2 py-0.5", TYPE_STYLES[type])}>
      {icon}{TYPE_LABELS[type]}
    </span>
  )
}

function RosBadge({ os }: { os: string }) {
  const v = rosVer(os)
  const cls = v >= 715
    ? "bg-[var(--status-online-bg)] text-[var(--status-online-fg)] border-current/20"
    : v >= 710
      ? "bg-[var(--status-degraded-bg)] text-[var(--status-degraded-fg)] border-current/20"
      : "bg-[var(--status-offline-bg)] text-[var(--status-offline-fg)] border-current/20"
  return <span className={cn("text-xs font-mono border rounded px-2 py-0.5", cls)}>{os}</span>
}

interface ServerRowActionsProps {
  server: Server
  isLive: boolean
  isPolling: boolean
  onEdit: (server: Server) => void
  onDelete: (id: string) => void
  onPoll: (id: string) => void
  onToggleStatus: (id: string) => void
}

function ServerRowActions({
  server,
  isLive,
  isPolling,
  onEdit,
  onDelete,
  onPoll,
  onToggleStatus,
}: ServerRowActionsProps) {
  return (
    <div
      className="flex justify-end"
      onClick={(e) => e.stopPropagation()}
      onKeyDown={(e) => e.stopPropagation()}
    >
      <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,background-color,color,border-color]",
                "group-hover/row:opacity-100 focus-visible:opacity-100",
                "data-popup-open:opacity-100 data-popup-open:bg-muted",
                "hover:bg-muted hover:text-foreground hover:border-border",
              )}
              onClick={(e) => e.stopPropagation()}
              aria-label={`Действия: ${server.name}`}
            >
              <MoreHorizontalIcon className="size-4" />
            </Button>
          }
        />
        <DropdownMenuContent align="end" side="bottom" className="w-52">
          <DropdownMenuItem onClick={() => window.open(`https://${server.host}`, "_blank")}>
            <ExternalLinkIcon className="size-4" />
            Открыть WebFig
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => onEdit(server)}>
            <PencilIcon className="size-4" />
            Редактировать
          </DropdownMenuItem>
          {isLive && (
            <DropdownMenuItem onClick={() => onPoll(server.id)} disabled={isPolling}>
              <RefreshCwIcon className={cn("size-4", isPolling && "animate-spin")} />
              {isPolling ? "Опрос…" : "Опросить"}
            </DropdownMenuItem>
          )}
          <DropdownMenuItem onClick={() => onToggleStatus(server.id)}>
            <PowerIcon className="size-4" />
            {server.status === "offline" ? "Включить" : "Отключить"}
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem variant="destructive" onClick={() => onDelete(server.id)}>
            <Trash2Icon className="size-4" />
            Удалить
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}

interface ServersDataGridProps {
  servers: Server[]
  isLive: boolean
  pollingIds: Set<string>
  onPoll: (id: string) => void
  onEdit: (server: Server) => void
  onDelete: (id: string) => void
  onToggleStatus: (id: string) => void
}

function ServersDataGrid({
  servers,
  isLive,
  pollingIds,
  onPoll,
  onEdit,
  onDelete,
  onToggleStatus,
}: ServersDataGridProps) {
  const columns = useMemo<ColumnDef<Server>[]>(
    () => [
      {
        id: "name",
        accessorKey: "name",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Имя / Хост" className="ml-1" />
        ),
        cell: ({ row }) => {
          const s = row.original
          const expanded = row.getIsExpanded()
          return (
            <div className="flex items-start gap-2 min-w-0">
              {expanded
                ? <ChevronDownIcon className="size-3.5 mt-0.5 shrink-0 text-muted-foreground" />
                : <ChevronRightIcon className="size-3.5 mt-0.5 shrink-0 text-muted-foreground/40" />}
              <div className="min-w-0">
                <p className="font-medium truncate">{s.name}</p>
                <p className="text-xs font-mono text-muted-foreground">{s.host}</p>
                {s.ipv6Address && (
                  <p className="text-[10px] font-mono text-sky-500/70 truncate max-w-[150px]" title={s.ipv6Address}>
                    {s.ipv6Address}
                  </p>
                )}
              </div>
            </div>
          )
        },
        meta: {
          headerTitle: "Имя / Хост",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
          expandedContent: (row: Server) => (
            <ServerExpandedDetail
              server={row}
              isLive={isLive}
              isPolling={pollingIds.has(row.id)}
              onPoll={() => onPoll(row.id)}
            />
          ),
        },
      },
      {
        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: "model",
        accessorKey: "model",
        header: ({ column }) => <DataGridSortHeader column={column} title="Модель" />,
        cell: ({ row }) => <span className="text-muted-foreground text-xs">{row.original.model}</span>,
        meta: { headerTitle: "Модель", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "os",
        accessorKey: "os",
        header: ({ column }) => <DataGridSortHeader column={column} title="RouterOS" />,
        cell: ({ row }) => <RosBadge os={row.original.os} />,
        meta: { headerTitle: "RouterOS", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "site",
        accessorKey: "site",
        header: ({ column }) => <DataGridSortHeader column={column} title="Площадка" />,
        cell: ({ row }) => (
          <div className="flex items-center gap-1.5">
            <Flag code={row.original.country} />
            <span className="font-medium text-sm">{row.original.site}</span>
          </div>
        ),
        meta: { headerTitle: "Площадка", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "wan",
        header: () => (
          <span className="text-xs font-medium text-muted-foreground">WAN / LAN</span>
        ),
        enableSorting: false,
        cell: ({ row }) => {
          const s = row.original
          if (s.type === "home-router" && s.wanUplinks?.length) {
            return (
              <div className="flex flex-col gap-0.5">
                {s.wanUplinks.map((w) => (
                  <div key={w.id} className="flex items-center gap-1.5 text-[11px] font-mono">
                    <WifiIcon className="size-3 text-sky-400 shrink-0" />
                    <span className="font-semibold text-sky-600 dark:text-sky-400">{w.name}</span>
                    <span className="text-muted-foreground">{w.isp}</span>
                    <span className="text-muted-foreground">↓{w.maxDl}↑{w.maxUl}</span>
                  </div>
                ))}
                {s.lanSubnet && (
                  <div className="text-[10px] font-mono text-muted-foreground mt-0.5">LAN {s.lanSubnet}</div>
                )}
              </div>
            )
          }
          return (
            <div className="flex flex-col gap-0.5">
              {s.wireGuardIfaces && s.wireGuardIfaces.length > 0 && (
                <div className="text-[11px] font-mono text-violet-500 dark:text-violet-400 flex items-center gap-1">
                  <ShieldIcon className="size-3" />
                  WG: {s.wireGuardIfaces.length} iface · {s.wireGuardIfaces.reduce((n, i) => n + i.peers.length, 0)} peers
                </div>
              )}
              {s.rpkiEnabled && (
                <div className="text-[10px] font-mono text-emerald-600 dark:text-emerald-400">RPKI ✓</div>
              )}
              {!s.wireGuardIfaces?.length && !s.rpkiEnabled && (
                <span className="text-xs text-muted-foreground">—</span>
              )}
            </div>
          )
        },
        meta: { headerTitle: "WAN / LAN", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "latency",
        accessorKey: "latency",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Задержка" className="w-full justify-end" />
        ),
        cell: ({ row }) => {
          const s = row.original
          return (
            <span className={cn(
              "font-mono text-sm block text-right tabular-nums",
              s.latency == null ? "text-muted-foreground" : s.latency > 60 ? "text-[var(--status-degraded-fg)]" : "",
            )}>
              {s.latency == null ? "—" : `${s.latency} мс`}
            </span>
          )
        },
        meta: {
          headerTitle: "Задержка",
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "status",
        accessorKey: "status",
        header: ({ column }) => <DataGridSortHeader column={column} title="Статус" />,
        cell: ({ row }) => <StatusBadge status={row.original.status} />,
        meta: { headerTitle: "Статус", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        cell: ({ row }) => {
          const s = row.original
          return (
            <ServerRowActions
              server={s}
              isLive={isLive}
              isPolling={pollingIds.has(s.id)}
              onEdit={onEdit}
              onDelete={onDelete}
              onPoll={onPoll}
              onToggleStatus={onToggleStatus}
            />
          )
        },
        enableSorting: false,
        size: 56,
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [isLive, onDelete, onEdit, onPoll, onToggleStatus, pollingIds],
  )

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

  if (servers.length === 0) {
    return (
      <EmptyState
        icon={<ServerIcon className="size-4" />}
        title="Нет серверов"
        description="Добавьте первый MikroTik-сервер для мониторинга"
        className="border-0 py-12"
      />
    )
  }

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

export { ServersDataGrid, rosVer, RosBadge, TypeBadge }
