"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
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 { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import { EmptyState } from "@/components/empty-state"
import {
  CheckIcon,
  ChevronRightIcon,
  CopyIcon,
  ServerIcon,
  TagIcon,
} from "lucide-react"

export type CommunityType = "standard" | "no-export" | "no-advertise" | "local-as" | "custom"

export interface CommunityRow {
  id: string
  value: string
  name: string
  description: string
  type: CommunityType
  filterIds: string[]
  serverCount: number
  prefixCount: number
  action: "permit" | "deny" | "local-pref" | "metric"
  actionValue?: number
  enabled: boolean
}

const TYPE_LABELS: Record<CommunityType, string> = {
  standard: "Стандартный",
  "no-export": "No-export",
  "no-advertise": "No-advertise",
  "local-as": "Local-AS",
  custom: "Кастомный",
}

const ACTION_LABELS: Record<CommunityRow["action"], string> = {
  permit: "Permit",
  deny: "Deny",
  "local-pref": "Local-pref",
  metric: "MED/Metric",
}

const ACTION_COLOR: Record<CommunityRow["action"], string> = {
  permit: "text-emerald-500",
  deny: "text-red-500",
  "local-pref": "text-blue-500",
  metric: "text-amber-500",
}

interface CommunitiesDataGridProps {
  communities: CommunityRow[]
  selectedId?: string | null
  copiedValue?: string | null
  onSelect: (community: CommunityRow) => void
  onCopy: (value: string) => void
}

function CommunitiesDataGrid({
  communities,
  selectedId,
  copiedValue,
  onSelect,
  onCopy,
}: CommunitiesDataGridProps) {
  const columns = useMemo<ColumnDef<CommunityRow>[]>(
    () => [
      {
        id: "value",
        accessorKey: "value",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Community" className="ml-1" />
        ),
        cell: ({ row }) => {
          const c = row.original
          return (
            <div
              className="flex items-center gap-2"
              data-community-disabled={!c.enabled ? true : undefined}
            >
              <TagIcon className="size-3.5 text-muted-foreground shrink-0" />
              <span className="font-mono text-xs font-medium bg-muted px-1.5 py-0.5 rounded">
                {c.value}
              </span>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation()
                  onCopy(c.value)
                }}
                className="text-muted-foreground/40 hover:text-muted-foreground transition-colors"
              >
                {copiedValue === c.value ? (
                  <CheckIcon className="size-3" />
                ) : (
                  <CopyIcon className="size-3" />
                )}
              </button>
            </div>
          )
        },
        meta: {
          headerTitle: "Community",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "name",
        accessorKey: "name",
        header: ({ column }) => <DataGridSortHeader column={column} title="Имя / описание" />,
        cell: ({ row }) => (
          <div className="min-w-0">
            <p className="font-medium text-xs">{row.original.name}</p>
            <p className="text-xs text-muted-foreground line-clamp-1">{row.original.description}</p>
          </div>
        ),
        meta: {
          headerTitle: "Имя / описание",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "type",
        accessorKey: "type",
        header: ({ column }) => <DataGridSortHeader column={column} title="Тип" />,
        cell: ({ row }) => (
          <span className="text-xs text-muted-foreground">
            {TYPE_LABELS[row.original.type]}
          </span>
        ),
        meta: {
          headerTitle: "Тип",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "action",
        accessorKey: "action",
        header: ({ column }) => <DataGridSortHeader column={column} title="Действие" />,
        cell: ({ row }) => {
          const c = row.original
          return (
            <span className={cn("text-xs font-medium", ACTION_COLOR[c.action])}>
              {ACTION_LABELS[c.action]}
              {c.actionValue !== undefined ? ` ${c.actionValue}` : ""}
            </span>
          )
        },
        meta: {
          headerTitle: "Действие",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "prefixCount",
        accessorKey: "prefixCount",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Маршрутов" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <span className="font-mono text-xs tabular-nums text-right block">
            {row.original.prefixCount.toLocaleString("ru-RU")}
          </span>
        ),
        meta: {
          headerTitle: "Маршрутов",
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "serverCount",
        accessorKey: "serverCount",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Серверов" className="ml-auto" />
        ),
        cell: ({ row }) => (
          <div className="flex items-center justify-end gap-1">
            <ServerIcon className="size-3 text-muted-foreground" />
            <span className="font-mono text-xs tabular-nums">
              {row.original.serverCount.toLocaleString("ru-RU")}
            </span>
          </div>
        ),
        meta: {
          headerTitle: "Серверов",
          headerClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
          cellClassName: cn(DATA_GRID_CELL_PAD, "text-right"),
        },
      },
      {
        id: "chevron",
        header: () => <span className="sr-only">Детали</span>,
        enableSorting: false,
        cell: () => <ChevronRightIcon className="size-4 text-muted-foreground/40" />,
        size: 40,
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [copiedValue, onCopy],
  )

  const rowSelection = useMemo(
    () => (selectedId ? { [selectedId]: true } : {}),
    [selectedId],
  )

  const table = useReactTable({
    data: communities,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getRowId: (row) => row.id,
    enableRowSelection: true,
    state: { rowSelection },
  })

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

  return (
    <DataGridShell
      table={table}
      recordCount={communities.length}
      onRowClick={(row) => onSelect(row)}
      tableClassNames={{
        headerRow: "border-b border-border",
        bodyRow: cn(
          "group/row",
          "data-[state=selected]:bg-primary/5",
          "[&:has([data-community-disabled=true])]:opacity-50",
        ),
      }}
    />
  )
}

export {
  CommunitiesDataGrid,
  type CommunitiesDataGridProps,
  TYPE_LABELS,
  ACTION_LABELS,
  ACTION_COLOR,
}
