"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { CommRec } from "@/lib/route-optimizer-data"
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 { ArrowRightIcon, PinIcon, RefreshCwIcon } from "lucide-react"

function Chip({ children, color }: { children: React.ReactNode; color?: string }) {
  return (
    <span
      className={cn(
        "inline-flex items-center rounded px-1.5 py-0.5 text-[11px] font-medium border",
        color ?? "bg-muted text-muted-foreground border-border",
      )}
    >
      {children}
    </span>
  )
}

function ProbChip({ prob, best }: { prob: number; best?: boolean }) {
  return (
    <Chip
      color={
        best
          ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20"
          : "bg-muted text-muted-foreground border-border"
      }
    >
      {prob}%
    </Chip>
  )
}

interface RouteOptimizerCommRecsDataGridProps {
  recs: CommRec[]
  homeId: string
  pinned: Set<string>
  applied: Set<string>
  applying: Set<string>
  onPin: (key: string) => void
  onApply: (community: string, homeId: string) => void
}

function RouteOptimizerCommRecsDataGrid({
  recs,
  homeId,
  pinned,
  applied,
  applying,
  onPin,
  onApply,
}: RouteOptimizerCommRecsDataGridProps) {
  const rows = useMemo(
    () => recs.map((r, idx) => ({ ...r, _rowKey: `${homeId}::${r.community}::${idx}` })),
    [homeId, recs],
  )

  const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(
    () => [
      {
        id: "community",
        accessorKey: "community",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Community" className="ml-1" />
        ),
        cell: ({ row }) => (
          <div>
            <div className="font-mono text-xs font-medium">{row.original.community}</div>
            <div className="text-[11px] text-muted-foreground">{row.original.communityName}</div>
          </div>
        ),
        meta: {
          headerTitle: "Community",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "current",
        header: () => (
          <span className="text-[11px] font-medium text-muted-foreground">
            Текущий (WAN → JH → Exit)
          </span>
        ),
        enableSorting: false,
        cell: ({ row }) => {
          const r = row.original
          if (!r.current) return <span className="text-muted-foreground text-xs">—</span>
          return (
            <div className="text-xs flex items-center gap-1 flex-wrap">
              <span className="font-mono font-medium text-sky-600 dark:text-sky-400">
                {r.current.wan}
              </span>
              <ArrowRightIcon className="size-3 text-muted-foreground shrink-0" />
              <span>{r.current.jh}</span>
              <ArrowRightIcon className="size-3 text-muted-foreground shrink-0" />
              <span className="text-muted-foreground">{r.current.exit}</span>
              <span className="font-mono text-[10px] text-muted-foreground">
                ({r.current.gateway})
              </span>
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "recommended",
        header: () => <span className="text-[11px] font-medium text-muted-foreground">Рекомендуемый</span>,
        enableSorting: false,
        cell: ({ row }) => {
          const r = row.original
          const pinKey = `${homeId}::${r.community}`
          const isPinned = pinned.has(pinKey)
          if (!r.recommended) return <span className="text-muted-foreground text-xs">—</span>
          return (
            <div
              className={cn(
                "text-xs flex items-center gap-1 flex-wrap",
                r.shouldSwitch && !isPinned && "text-amber-600 dark:text-amber-400",
              )}
            >
              <span className="font-mono font-medium">{r.recommended.wan}</span>
              <ArrowRightIcon className="size-3 shrink-0 opacity-60" />
              <span>{r.recommended.jh}</span>
              <ArrowRightIcon className="size-3 shrink-0 opacity-60" />
              <span>{r.recommended.exit}</span>
              {r.shouldSwitch && !isPinned && (
                <span className="ml-1 text-[10px] font-bold bg-amber-500/10 border border-amber-500/20 px-1.5 py-0.5 rounded">
                  +{(r.recommended.prob ?? 0) - (r.current?.prob ?? 0)}%
                </span>
              )}
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "probability",
        header: () => (
          <span className="text-[11px] font-medium text-muted-foreground block text-center">
            P(тек / рек)
          </span>
        ),
        enableSorting: false,
        cell: ({ row }) => {
          const r = row.original
          const pinKey = `${homeId}::${r.community}`
          return (
            <div className="flex items-center justify-center gap-1">
              <ProbChip prob={r.current?.prob ?? 0} />
              <span className="text-muted-foreground text-[10px]">/</span>
              <ProbChip prob={r.recommended?.prob ?? 0} best={r.shouldSwitch && !pinned.has(pinKey)} />
            </div>
          )
        },
        meta: {
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-center"),
        },
      },
      {
        id: "actions",
        header: () => (
          <span className="text-[11px] font-medium text-muted-foreground block text-right">
            Действие
          </span>
        ),
        enableSorting: false,
        cell: ({ row }) => {
          const r = row.original
          const pinKey = `${homeId}::${r.community}`
          const isPinned = pinned.has(pinKey)
          const isApplied = applied.has(pinKey)
          const isApplying = applying.has(pinKey)
          const canApply = r.shouldSwitch && !isPinned && !isApplied
          return (
            <div className="flex items-center justify-end gap-1.5" onClick={(e) => e.stopPropagation()}>
              {isPinned && <PinIcon className="size-3 text-sky-500 fill-sky-500" />}
              <Button
                variant="outline"
                size="sm"
                className={cn("h-7 text-xs", isPinned && "text-sky-600 dark:text-sky-400 border-sky-500/30")}
                onClick={() => onPin(pinKey)}
              >
                <PinIcon className={cn("size-3", isPinned && "fill-current")} />
                {isPinned ? "Открепить" : "Закрепить"}
              </Button>
              {canApply && (
                <Button
                  size="sm"
                  className="h-7 text-xs"
                  disabled={isApplying}
                  onClick={() => onApply(r.community, homeId)}
                >
                  {isApplying ? (
                    <RefreshCwIcon className="size-3 animate-spin" />
                  ) : (
                    "Применить"
                  )}
                </Button>
              )}
              {isApplied && (
                <span className="text-[10px] text-emerald-600 dark:text-emerald-400 font-medium">
                  ✓ применено
                </span>
              )}
            </div>
          )
        },
        meta: {
          headerClassName: cn(DATA_GRID_CELL_PAD_LAST, "text-right"),
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [applied, applying, homeId, onApply, onPin, pinned],
  )

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

  return (
    <DataGridShell
      table={table}
      recordCount={rows.length}
      tableClassNames={{
        headerRow: "border-b bg-muted/20",
        bodyRow: cn(
          "group/row hover:bg-muted/30",
          "[&:has([data-comm-switch=true])]:bg-amber-500/5",
          "[&:has([data-comm-applied=true])]:bg-emerald-500/5",
        ),
      }}
      tableLayout={{ dense: true }}
    />
  )
}

export { RouteOptimizerCommRecsDataGrid, type RouteOptimizerCommRecsDataGridProps }
