"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { GrePool } from "@/lib/data"
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 { LayersIcon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from "lucide-react"

interface GrePoolsDataGridProps {
  pools: GrePool[]
}

function GrePoolsDataGrid({ pools }: GrePoolsDataGridProps) {
  const columns = useMemo<ColumnDef<GrePool>[]>(
    () => [
      {
        id: "name",
        accessorKey: "name",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Имя пула" className="ml-1" />
        ),
        cell: ({ row }) => (
          <span className="font-mono text-[13px] font-medium">{row.original.name}</span>
        ),
        meta: {
          headerTitle: "Имя пула",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "cidr",
        accessorKey: "cidr",
        header: ({ column }) => <DataGridSortHeader column={column} title="Диапазон CIDR" />,
        cell: ({ row }) => <span className="font-mono text-xs">{row.original.cidr}</span>,
        meta: {
          headerTitle: "Диапазон CIDR",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "allocated",
        accessorKey: "allocated",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Назначено /30" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <span className="tabular-nums text-right block">{row.original.allocated}</span>
        ),
        meta: {
          headerTitle: "Назначено /30",
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "available",
        header: () => (
          <span className="text-xs font-medium text-muted-foreground block text-right">
            Доступно /30
          </span>
        ),
        enableSorting: false,
        cell: ({ row }) => {
          const p = row.original
          return (
            <span className="tabular-nums text-muted-foreground text-right block">
              {p.total - p.allocated}
            </span>
          )
        },
        meta: {
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "usage",
        header: () => <span className="text-xs font-medium text-muted-foreground">Использование</span>,
        enableSorting: false,
        cell: ({ row }) => {
          const pool = row.original
          const pct = pool.total > 0 ? Math.round((pool.allocated / pool.total) * 100) : 0
          return (
            <div className="flex items-center gap-2 min-w-[140px]">
              <div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
                <div
                  className={cn("h-full rounded-full", pct > 80 ? "bg-amber-500" : "bg-emerald-500")}
                  style={{ width: `${pct}%` }}
                />
              </div>
              <span className="text-xs text-muted-foreground tabular-nums w-8 text-right">{pct}%</span>
            </div>
          )
        },
        meta: { headerClassName: DATA_GRID_CELL_PAD, cellClassName: DATA_GRID_CELL_PAD },
      },
      {
        id: "comment",
        accessorKey: "comment",
        header: ({ column }) => <DataGridSortHeader column={column} title="Назначение" />,
        cell: ({ row }) => (
          <span className="text-muted-foreground text-xs">{row.original.comment}</span>
        ),
        meta: {
          headerTitle: "Назначение",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        enableSorting: false,
        cell: () => (
          <div className="flex justify-end">
            <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 group-hover/row:opacity-100 focus-visible:opacity-100",
                      "data-popup-open:opacity-100",
                    )}
                  >
                    <MoreHorizontalIcon className="size-4" />
                  </Button>
                }
              />
              <DropdownMenuContent side="bottom" align="end">
                <DropdownMenuItem>
                  <PencilIcon className="size-4" /> Редактировать
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem variant="destructive">
                  <Trash2Icon className="size-4" /> Удалить пул
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        ),
        size: 56,
        meta: { headerClassName: DATA_GRID_CELL_PAD_LAST, cellClassName: DATA_GRID_CELL_PAD_LAST },
      },
    ],
    [],
  )

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

  if (pools.length === 0) {
    return (
      <EmptyState
        icon={<LayersIcon className="size-4" />}
        title="Нет IP-пулов"
        className="border-0 py-16"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={pools.length}
      tableClassNames={{ headerRow: "border-b border-border", bodyRow: "group/row" }}
    />
  )
}

export { GrePoolsDataGrid, type GrePoolsDataGridProps }
