"use client"

import { useMemo } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { Backup } from "@/lib/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 { EmptyState } from "@/components/empty-state"
import { DownloadIcon, HardDriveIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"

interface BackupsDataGridProps {
  backups: Backup[]
  onDownload: (id: string, filename: string) => void
  onRestore: (backup: Backup) => void
  onDelete: (id: string) => void
}

function BackupsDataGrid({
  backups,
  onDownload,
  onRestore,
  onDelete,
}: BackupsDataGridProps) {
  const columns = useMemo<ColumnDef<Backup>[]>(
    () => [
      {
        id: "filename",
        accessorKey: "filename",
        header: ({ column }) => <DataGridSortHeader column={column} title="Файл" />,
        cell: ({ row }) => (
          <span className="font-mono text-xs font-medium">{row.original.filename}</span>
        ),
        meta: {
          headerTitle: "Файл",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
        },
      },
      {
        id: "server",
        accessorKey: "server",
        header: ({ column }) => <DataGridSortHeader column={column} title="Сервер" />,
        cell: ({ row }) => (
          <span className="text-sm text-muted-foreground">{row.original.server}</span>
        ),
        meta: {
          headerTitle: "Сервер",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "size",
        accessorKey: "size",
        header: ({ column }) => <DataGridSortHeader column={column} title="Размер" />,
        cell: ({ row }) => (
          <span className="font-mono text-xs text-muted-foreground">{row.original.size}</span>
        ),
        meta: {
          headerTitle: "Размер",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "kind",
        accessorKey: "kind",
        header: ({ column }) => <DataGridSortHeader column={column} title="Тип" />,
        cell: ({ row }) => {
          const kind = row.original.kind
          return (
            <span
              className={cn(
                "text-xs px-2 py-0.5 rounded border font-medium",
                kind === "manual"
                  ? "bg-blue-500/10 text-blue-400 border-blue-500/20"
                  : "bg-muted text-muted-foreground border-border",
              )}
            >
              {kind === "auto" ? "авто" : "вручную"}
            </span>
          )
        },
        meta: {
          headerTitle: "Тип",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "notes",
        accessorKey: "notes",
        header: ({ column }) => <DataGridSortHeader column={column} title="Заметки" />,
        cell: ({ row }) => (
          <span className="text-xs text-muted-foreground max-w-[200px] truncate block">
            {row.original.notes || "—"}
          </span>
        ),
        meta: {
          headerTitle: "Заметки",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "created",
        accessorKey: "created",
        header: ({ column }) => <DataGridSortHeader column={column} title="Создан" />,
        cell: ({ row }) => (
          <span className="text-xs text-muted-foreground">{row.original.created}</span>
        ),
        meta: {
          headerTitle: "Создан",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "actions",
        header: () => <span className="sr-only">Действия</span>,
        cell: ({ row }) => {
          const b = row.original
          return (
            <div className="flex items-center gap-1 justify-end opacity-0 transition-opacity group-hover/row:opacity-100 focus-within:opacity-100">
              <Button
                variant="ghost"
                size="icon"
                className="size-7"
                title="Скачать"
                onClick={() => onDownload(b.id, b.filename)}
              >
                <DownloadIcon className="size-3.5" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="size-7"
                title="Восстановить"
                onClick={() => onRestore(b)}
              >
                <RefreshCwIcon className="size-3.5" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="size-7 text-destructive hover:text-destructive"
                title="Удалить"
                onClick={() => onDelete(b.id)}
              >
                <Trash2Icon className="size-3.5" />
              </Button>
            </div>
          )
        },
        enableSorting: false,
        size: 120,
        meta: {
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [onDelete, onDownload, onRestore],
  )

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

  if (backups.length === 0) {
    return (
      <EmptyState
        icon={<HardDriveIcon className="size-4" />}
        title="Нет бэкапов"
        description="Создайте первый бэкап вручную или настройте расписание"
        className="border-0 py-10"
      />
    )
  }

  return <DataGridShell table={table} recordCount={backups.length} />
}

export { BackupsDataGrid, type BackupsDataGridProps }
