"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { HomeRouter, JumpHost, WanJhLeg } from "@/lib/route-optimizer-data"
import { Flag } from "@/components/flag"
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,
  DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/data-grid-layout"
import { WifiIcon } from "lucide-react"

function LossChip({ loss }: { loss: number }) {
  if (loss === 0) return <span className="text-emerald-600 dark:text-emerald-400 text-[11px] font-mono">0%</span>
  return (
    <span className={cn("text-[11px] font-mono", loss > 1 ? "text-red-500" : "text-amber-500")}>
      {loss}%
    </span>
  )
}

interface RouteOptimizerWanMatrixDataGridProps {
  home: HomeRouter
  legs: WanJhLeg[]
  jumpHosts: JumpHost[]
}

function RouteOptimizerWanMatrixDataGrid({
  home,
  legs,
  jumpHosts,
}: RouteOptimizerWanMatrixDataGridProps) {
  const bestScore = legs.length ? Math.max(...legs.map((l) => l.score)) : 0

  const columns = useMemo<ColumnDef<HomeRouter["wans"][number]>[]>(() => {
    const base: ColumnDef<HomeRouter["wans"][number]>[] = [
      {
        id: "wan",
        accessorKey: "name",
        header: () => <span className="text-[11px] font-medium text-muted-foreground">WAN-аплинк</span>,
        cell: ({ row }) => {
          const wan = row.original
          return (
            <div className="flex items-center gap-2">
              <WifiIcon className="size-3.5 text-muted-foreground shrink-0" />
              <div>
                <p className="font-mono text-xs font-semibold">{wan.name}</p>
                <p className="text-[10px] text-muted-foreground">{wan.iface}</p>
              </div>
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD_FIRST, cellClassName: DATA_GRID_CELL_PAD_FIRST },
      },
      {
        id: "isp",
        header: () => <span className="text-[11px] font-medium text-muted-foreground">ISP / IP</span>,
        cell: ({ row }) => {
          const wan = row.original
          return (
            <div>
              <p className="text-xs font-medium">{wan.isp}</p>
              <p className="font-mono text-[10px] text-muted-foreground">{wan.ip}</p>
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "bandwidth",
        header: () => (
          <span className="text-[11px] font-medium text-muted-foreground block text-right">
            Макс. полоса
          </span>
        ),
        cell: ({ row }) => {
          const wan = row.original
          return (
            <div className="text-right">
              <p className="font-mono text-xs">↓{wan.maxDl}</p>
              <p className="font-mono text-[10px] text-muted-foreground">↑{wan.maxUl} Мбит</p>
            </div>
          )
        },
        meta: {
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
    ]

    const jhCols: ColumnDef<HomeRouter["wans"][number]>[] = jumpHosts.map((jh) => ({
      id: `jh-${jh.id}`,
      header: () => (
        <div className="text-center">
          <div className="text-[11px] font-medium text-muted-foreground">{jh.label}</div>
          <div className="font-mono font-normal text-[10px] opacity-60 flex items-center justify-center gap-1">
            <Flag code={jh.country} />
            {jh.site} · {jh.ip}
          </div>
        </div>
      ),
      cell: ({ row }) => {
        const wan = row.original
        const leg = legs.find((l) => l.wanId === wan.id && l.jhId === jh.id)
        if (!leg) return <span className="text-center text-muted-foreground text-xs block">—</span>
        const isBest = leg.score === bestScore
        return (
          <div className={cn("text-center", isBest && "bg-emerald-500/5")}>
            <div
              className={cn(
                "flex flex-col items-center gap-0.5 rounded-md px-2 py-1.5 transition-colors",
                isBest ? "border border-emerald-500/20 bg-emerald-500/8" : "border border-transparent",
              )}
            >
              {isBest && (
                <span className="text-[9px] font-bold uppercase tracking-wide text-emerald-600 dark:text-emerald-400 mb-0.5">
                  ★ ЛУЧШИЙ
                </span>
              )}
              <span
                className={cn(
                  "font-mono text-xs font-semibold",
                  leg.pingMs < 10
                    ? "text-emerald-600 dark:text-emerald-400"
                    : leg.pingMs < 25
                      ? "text-foreground"
                      : "text-amber-600 dark:text-amber-400",
                )}
              >
                {leg.pingMs} мс
              </span>
              <span className="text-[10px] text-muted-foreground font-mono">
                ↓{leg.dlMbps} ↑{leg.ulMbps}
              </span>
              <div className="flex items-center gap-1.5 mt-0.5">
                <span className="text-[10px] font-mono text-foreground/70">score {leg.score}</span>
                {leg.loss > 0 && <LossChip loss={leg.loss} />}
              </div>
            </div>
          </div>
        )
      },
      meta: {
        headerClassName: cn(DATA_GRID_CELL_PAD, "min-w-[130px] text-center"),
        cellClassName: cn(DATA_GRID_CELL_PAD, "min-w-[130px]"),
      },
    }))

    const last = jhCols[jhCols.length - 1]
    if (last?.meta) {
      last.meta.headerClassName = cn(last.meta.headerClassName, DATA_GRID_CELL_PAD_LAST.replace("py-3", ""))
      last.meta.cellClassName = DATA_GRID_CELL_PAD_LAST
    }

    return [...base, ...jhCols]
  }, [bestScore, jumpHosts, legs])

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

  return (
    <DataGridShell
      table={table}
      recordCount={home.wans.length}
      tableClassNames={{ headerRow: "border-b bg-muted/20", bodyRow: "group/row hover:bg-muted/30" }}
      tableLayout={{ dense: true }}
    />
  )
}

export { RouteOptimizerWanMatrixDataGrid, type RouteOptimizerWanMatrixDataGridProps }
