"use client"

import { useMemo, useState } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { FilterRule, GreTunnel, Server } from "@/lib/data"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
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 {
  AlertCircleIcon,
  AlertTriangleIcon,
  CheckCircle2Icon,
  ChevronDownIcon,
  ChevronUpIcon,
  CircleDashedIcon,
  PencilIcon,
  RouteIcon,
  StarIcon,
  TrashIcon,
  XCircleIcon,
  FilterIcon,
} from "lucide-react"

export type FilterRouterSyncStatus = "synced" | "drift" | "missing"

export interface RecursiveRouteLite {
  id: string
  dstAddress: string
  gateway: string
  distance: number
  routingTable: string
  comment: string
  disabled: boolean
}

function RouterSyncMarker({
  status,
}: {
  status: FilterRouterSyncStatus | null | "skip"
}) {
  if (status === "skip") {
    return <span className="size-3.5 shrink-0 block" aria-hidden />
  }
  const icon =
    status === "synced"
      ? <CheckCircle2Icon className="size-3.5 text-emerald-600 dark:text-emerald-500 shrink-0" />
      : status === "drift"
        ? <AlertTriangleIcon className="size-3.5 text-amber-500 shrink-0" />
        : status === "missing"
          ? <XCircleIcon className="size-3.5 text-destructive shrink-0" />
          : <CircleDashedIcon className="size-3.5 text-muted-foreground/35 shrink-0" />
  const title =
    status === "synced"
      ? "Совпадает с цепочкой bgp-in на MikroTik"
      : status === "drift"
        ? "В БД и на роутере разное действие (gateway, blackhole или out-interface)"
        : status === "missing"
          ? "Эта community не найдена в правиле bgp-in на роутере"
          : "Не проверено — нажмите «Сверить с роутером»"
  return (
    <Tooltip>
      <TooltipTrigger className="inline-flex cursor-default border-0 bg-transparent p-0">
        {icon}
      </TooltipTrigger>
      <TooltipContent side="top" className="max-w-xs">
        {title}
      </TooltipContent>
    </Tooltip>
  )
}

function innerIpToGateway(ip: string) {
  return ip.split("/")[0]
}

function gatewayFromRecursiveDst(dstAddress: string) {
  return innerIpToGateway((dstAddress ?? "").trim())
}

function pickRecursiveRouteByGatewayHop(routes: RecursiveRouteLite[], hopIp: string) {
  const hop = hopIp.trim()
  if (!hop) return undefined
  const candidates = routes.filter(
    (r) => !r.disabled && gatewayFromRecursiveDst(r.dstAddress) === hop,
  )
  if (candidates.length === 0) return undefined
  return candidates.reduce((a, b) => (a.distance <= b.distance ? a : b))
}

function isRecursiveGatewayRef(ref: string) {
  return ref.startsWith("rec:")
}

function FilterGatewayCell({
  rule,
  tunnelsList,
  serversList,
  recursiveRoutes,
}: {
  rule: FilterRule
  tunnelsList: GreTunnel[]
  serversList: Server[]
  recursiveRoutes: RecursiveRouteLite[]
}) {
  const isBlackhole = rule.action === "blackhole"
  const isRecRef = !isBlackhole && isRecursiveGatewayRef(rule.gatewayTunnelId)
  const recRowByRef = isRecRef
    ? recursiveRoutes.find((r) => r.id === rule.gatewayTunnelId.slice(4))
    : undefined
  const recRowByHop =
    !isBlackhole && !(rule.gatewayTunnelId ?? "").trim() && rule.gateway.trim()
      ? pickRecursiveRouteByGatewayHop(recursiveRoutes, rule.gateway)
      : undefined
  const recRow = recRowByRef ?? recRowByHop
  const treatAsRecursive = !isBlackhole && (isRecRef || !!recRowByHop)
  const tunnel =
    !isBlackhole && !treatAsRecursive
      ? tunnelsList.find((t) => t.id === rule.gatewayTunnelId)
      : undefined
  const remoteSrv = tunnel ? serversList.find((s) => s.host === tunnel.remoteAddress) : undefined

  if (isBlackhole) {
    return (
      <div className="flex items-center gap-1.5">
        <span className="size-1.5 rounded-full shrink-0 bg-red-500 animate-pulse" />
        <span className="font-mono text-xs font-medium text-red-600 dark:text-red-400">type=blackhole</span>
      </div>
    )
  }

  return (
    <div className="min-w-0 flex flex-col gap-0.5">
      <div className="flex items-center gap-1.5 flex-wrap">
        <span
          className={cn(
            "size-1.5 rounded-full shrink-0",
            treatAsRecursive
              ? "bg-sky-500"
              : tunnel?.status === "up"
                ? "bg-[var(--status-online)]"
                : tunnel?.status === "degraded"
                  ? "bg-[var(--status-degraded)]"
                  : "bg-[var(--status-offline)]",
          )}
        />
        {treatAsRecursive ? (
          <>
            <RouteIcon className="size-3 text-muted-foreground shrink-0" />
            <span className="font-mono text-xs font-medium">
              {recRow ? gatewayFromRecursiveDst(recRow.dstAddress) : rule.gateway}
            </span>
            <span className="text-[10px] font-medium text-muted-foreground border border-border rounded px-1 uppercase tracking-wide">
              recursive
            </span>
          </>
        ) : (
          <>
            {remoteSrv && <Flag code={remoteSrv.country} />}
            <span className="font-mono text-xs font-medium">{rule.gateway}</span>
          </>
        )}
      </div>
      {treatAsRecursive ? (
        recRow ? (
          <p className="text-[11px] text-muted-foreground truncate pl-3">{recRow.dstAddress}</p>
        ) : isRecRef ? (
          <p className="text-[11px] text-amber-600 dark:text-amber-400 truncate pl-3">
            рекурсивный маршрут (нет строки в списке)
          </p>
        ) : null
      ) : tunnel ? (
        <p className="text-[11px] text-muted-foreground truncate pl-3">{tunnel.name}</p>
      ) : null}
    </div>
  )
}

function FilterRowActions({
  onEdit,
  onDelete,
}: {
  onEdit: () => void
  onDelete: () => void
}) {
  const [confirmDel, setConfirmDel] = useState(false)
  return (
    <div className="flex items-center gap-0.5 justify-end opacity-0 transition-opacity group-hover/row:opacity-100 focus-within:opacity-100">
      <Button
        size="sm"
        variant="ghost"
        className="size-7 p-0 text-muted-foreground hover:text-foreground"
        onClick={onEdit}
      >
        <PencilIcon className="size-3.5" />
      </Button>
      <Button
        size="sm"
        variant="ghost"
        className={cn(
          "size-7 p-0 transition-colors",
          confirmDel
            ? "text-destructive bg-destructive/10 hover:bg-destructive/20"
            : "text-muted-foreground hover:text-destructive",
        )}
        onClick={() => {
          if (!confirmDel) setConfirmDel(true)
          else onDelete()
        }}
        onBlur={() => setConfirmDel(false)}
      >
        {confirmDel ? <AlertCircleIcon className="size-3.5" /> : <TrashIcon className="size-3.5" />}
      </Button>
    </div>
  )
}

interface FiltersDataGridProps {
  rules: FilterRule[]
  tunnelsList: GreTunnel[]
  serversList: Server[]
  communityNameMap: Record<string, string>
  recursiveRoutes: RecursiveRouteLite[]
  routerSyncByCommunity?: Record<string, FilterRouterSyncStatus> | null
  isLive?: boolean
  enableSorting?: boolean
  onEdit: (rule: FilterRule) => void
  onDelete: (id: string) => void
  onMoveUp: (id: string) => void
  onMoveDown: (id: string) => void
}

function FiltersDataGrid({
  rules,
  tunnelsList,
  serversList,
  communityNameMap,
  recursiveRoutes,
  routerSyncByCommunity,
  isLive,
  enableSorting = false,
  onEdit,
  onDelete,
  onMoveUp,
  onMoveDown,
}: FiltersDataGridProps) {
  const columns = useMemo<ColumnDef<FilterRule>[]>(
    () => [
      {
        id: "priority",
        header: () => <span className="text-xs font-medium text-muted-foreground">#</span>,
        enableSorting: false,
        cell: ({ row, table }) => {
          const isLast = row.index === table.getRowModel().rows.length - 1
          return (
            <div className="flex items-center justify-center text-[11px] font-mono text-muted-foreground/40">
              {isLast ? (
                <StarIcon className="size-3 text-amber-400 fill-amber-400" aria-label="Наивысший приоритет" />
              ) : (
                <span>{row.index + 1}</span>
              )}
            </div>
          )
        },
        size: 28,
        meta: { headerClassName: DATA_GRID_CELL_PAD_FIRST, cellClassName: DATA_GRID_CELL_PAD_FIRST },
      },
      {
        id: "reorder",
        header: () => <span className="sr-only">Порядок</span>,
        enableSorting: false,
        cell: ({ row, table }) => {
          const isLast = row.index === table.getRowModel().rows.length - 1
          return (
            <div className="flex flex-col gap-px opacity-0 transition-opacity group-hover/row:opacity-100 focus-within:opacity-100">
              <button
                type="button"
                onClick={() => onMoveUp(row.original.id)}
                disabled={row.index === 0}
                className="text-muted-foreground/50 hover:text-foreground disabled:opacity-20"
              >
                <ChevronUpIcon className="size-3" />
              </button>
              <button
                type="button"
                onClick={() => onMoveDown(row.original.id)}
                disabled={isLast}
                className="text-muted-foreground/50 hover:text-foreground disabled:opacity-20"
              >
                <ChevronDownIcon className="size-3" />
              </button>
            </div>
          )
        },
        size: 28,
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "routerSync",
        header: () => (
          <Tooltip>
            <TooltipTrigger className="cursor-help font-mono text-xs text-muted-foreground border-0 bg-transparent p-0">
              MT
            </TooltipTrigger>
            <TooltipContent side="top" className="max-w-xs">
              Совпадение с MikroTik (bgp-in)
            </TooltipContent>
          </Tooltip>
        ),
        enableSorting: false,
        cell: ({ row }) => (
          <RouterSyncMarker
            status={
              !isLive
                ? "skip"
                : !routerSyncByCommunity
                  ? null
                  : routerSyncByCommunity[row.original.community.trim()] ?? null
            }
          />
        ),
        size: 32,
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "community",
        accessorKey: "community",
        header: ({ column }) => <DataGridSortHeader column={column} title="Community" />,
        enableSorting,
        cell: ({ row }) => {
          const rule = row.original
          const isBlackhole = rule.action === "blackhole"
          const communityName = communityNameMap[rule.community] ?? rule.communityName
          return (
            <div className="min-w-0">
              <div className="flex items-center gap-1.5 flex-wrap">
                <span
                  className={cn(
                    "inline-flex items-center rounded px-1.5 py-0.5 text-[11px] font-medium border font-mono",
                    isBlackhole
                      ? "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/25"
                      : "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
                  )}
                >
                  {rule.community}
                </span>
                {isBlackhole && (
                  <span className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-semibold border bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20 uppercase">
                    ⊘ blackhole
                  </span>
                )}
              </div>
              {communityName && (
                <p className="text-[11px] text-muted-foreground mt-0.5 truncate">{communityName}</p>
              )}
            </div>
          )
        },
        meta: { headerTitle: "Community", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "gateway",
        accessorKey: "gateway",
        header: ({ column }) => <DataGridSortHeader column={column} title="Gateway" />,
        enableSorting,
        cell: ({ row }) => (
          <FilterGatewayCell
            rule={row.original}
            tunnelsList={tunnelsList}
            serversList={serversList}
            recursiveRoutes={recursiveRoutes}
          />
        ),
        meta: { headerTitle: "Gateway", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "description",
        accessorKey: "description",
        header: ({ column }) => <DataGridSortHeader column={column} title="Описание" />,
        enableSorting,
        cell: ({ row }) => (
          <p className="text-xs text-muted-foreground truncate">{row.original.description || "—"}</p>
        ),
        meta: { headerTitle: "Описание", headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <FilterRowActions
            onEdit={() => onEdit(row.original)}
            onDelete={() => onDelete(row.original.id)}
          />
        ),
        size: 64,
        meta: { headerClassName: DATA_GRID_CELL_PAD_LAST, cellClassName: DATA_GRID_CELL_PAD_LAST },
      },
    ],
    [
      communityNameMap,
      enableSorting,
      isLive,
      onDelete,
      onEdit,
      onMoveDown,
      onMoveUp,
      recursiveRoutes,
      routerSyncByCommunity,
      serversList,
      tunnelsList,
    ],
  )

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

  if (rules.length === 0) {
    return (
      <EmptyState
        icon={<FilterIcon className="size-4" />}
        title="Ничего не найдено"
        className="border-0 py-16"
      />
    )
  }

  return (
    <>
      <DataGridShell table={table} recordCount={rules.length} />
      <div className="px-5 py-2 text-[11px] text-muted-foreground/40 flex items-center gap-1.5 border-t">
        <StarIcon className="size-3 text-amber-400 fill-amber-400 shrink-0" />
        Последнее правило имеет наивысший приоритет в RouterOS
      </div>
    </>
  )
}

export { FiltersDataGrid, RouterSyncMarker, type FiltersDataGridProps }
