"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { ActionBadge, ChainBadge } from "@/components/data-grids/firewall-rules-data-grid"
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 { cn } from "@/lib/utils"
import { PowerIcon, Trash2Icon } from "lucide-react"

function ScenarioCell({ enabled, children }: { enabled: boolean; children: React.ReactNode }) {
  return <div className={cn(!enabled && "opacity-40")}>{children}</div>
}

export interface ScenarioRuleRow {
  id: string
  chain: string
  action: string
  proto: string
  src: string
  dst: string
  port: string
  iface: string
  comment: string
  enabled: boolean
}

interface FirewallScenarioRulesDataGridProps {
  rules: ScenarioRuleRow[]
  onToggleEnabled: (id: string) => void
  onMoveUp: (id: string) => void
  onMoveDown: (id: string) => void
  onRemove: (id: string) => void
}

function FirewallScenarioRulesDataGrid({
  rules,
  onToggleEnabled,
  onMoveUp,
  onMoveDown,
  onRemove,
}: FirewallScenarioRulesDataGridProps) {
  const indexedRules = useMemo(
    () => rules.map((rule, index) => ({ ...rule, _index: index + 1 })),
    [rules],
  )

  const columns = useMemo<ColumnDef<ScenarioRuleRow & { _index: number }>[]>(
    () => [
      {
        id: "index",
        accessorKey: "_index",
        header: () => <span className="text-xs font-medium text-muted-foreground">#</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <ScenarioCell enabled={row.original.enabled}>
            <span className="font-mono text-xs text-muted-foreground tabular-nums">{row.original._index}</span>
          </ScenarioCell>
        ),
        size: 40,
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "chain",
        accessorKey: "chain",
        header: () => <span className="text-xs font-medium text-muted-foreground">Цепочка</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <ScenarioCell enabled={row.original.enabled}>
            <ChainBadge chain={row.original.chain} />
          </ScenarioCell>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "action",
        accessorKey: "action",
        header: () => <span className="text-xs font-medium text-muted-foreground">Действие</span>,
        enableSorting: false,
        cell: ({ row }) => <ActionBadge action={row.original.action} />,
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "src",
        accessorKey: "src",
        header: () => <span className="text-xs font-medium text-muted-foreground">Src</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span className="font-mono text-xs text-muted-foreground max-w-[90px] truncate block">
            {row.original.src || "any"}
          </span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "dst",
        accessorKey: "dst",
        header: () => <span className="text-xs font-medium text-muted-foreground">Dst</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span className="font-mono text-xs text-muted-foreground max-w-[90px] truncate block">
            {row.original.dst || "any"}
          </span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "port",
        accessorKey: "port",
        header: () => <span className="text-xs font-medium text-muted-foreground">Порт</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span className="font-mono text-xs text-muted-foreground">{row.original.port || "—"}</span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "iface",
        accessorKey: "iface",
        header: () => <span className="text-xs font-medium text-muted-foreground">Iface</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span className="font-mono text-xs text-muted-foreground">{row.original.iface || "—"}</span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "comment",
        accessorKey: "comment",
        header: () => <span className="text-xs font-medium text-muted-foreground">Комментарий</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <span className="text-xs text-muted-foreground/70 max-w-[110px] truncate block">
            {row.original.comment || "—"}
          </span>
        ),
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "actions",
        header: () => null,
        enableSorting: false,
        cell: ({ row }) => {
          const index = row.original._index - 1
          return (
            <div className="flex items-center gap-0.5 justify-end opacity-0 group-hover/row:opacity-100 transition-opacity">
              <button
                type="button"
                onClick={() => onToggleEnabled(row.original.id)}
                title={row.original.enabled ? "Отключить" : "Включить"}
                className="p-0.5 text-muted-foreground/40 hover:text-foreground transition-colors"
              >
                <PowerIcon className="size-3.5" />
              </button>
              <button
                type="button"
                onClick={() => onMoveUp(row.original.id)}
                disabled={index === 0}
                className="p-0.5 text-muted-foreground/40 hover:text-foreground disabled:opacity-20 transition-colors"
              >
                ▲
              </button>
              <button
                type="button"
                onClick={() => onMoveDown(row.original.id)}
                disabled={index === rules.length - 1}
                className="p-0.5 text-muted-foreground/40 hover:text-foreground disabled:opacity-20 transition-colors"
              >
                ▼
              </button>
              <button
                type="button"
                onClick={() => onRemove(row.original.id)}
                className="p-0.5 ml-0.5 text-muted-foreground/40 hover:text-red-500 transition-colors"
              >
                <Trash2Icon className="size-3.5" />
              </button>
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD_LAST, cellClassName: DATA_GRID_CELL_PAD_LAST },
      },
    ],
    [onMoveDown, onMoveUp, onRemove, onToggleEnabled, rules.length],
  )

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

  return (
    <DataGridShell
      table={table}
      recordCount={rules.length}
      tableClassNames={{
        bodyRow: cn("group/row text-xs", "hover:bg-muted/20 transition-colors"),
      }}
    />
  )
}

export { FirewallScenarioRulesDataGrid, type FirewallScenarioRulesDataGridProps }
