"use client";

import * as React from "react";

import {
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  useReactTable,
  type ColumnDef,
  type PaginationState,
} from "@tanstack/react-table";

import {
  DataTablePagination,
  DataTableShell,
  matchesText,
} from "@/app/dashboard/_components/data-table";
import { RbacRowActions } from "@/components/admins/rbac/rbac-row-actions";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import type { PermissionCatalogEntry } from "./types";
import { formatDisplayDate } from "@/lib/format/dates";

type PermissionsCatalogTableProps = {
  data: PermissionCatalogEntry[];
  onView?: (permissionName: string) => void;
  onDelete?: (permissionName: string) => void;
  viewingPermissionName?: string | null;
  deletingPermissionName?: string | null;
};

export function PermissionsCatalogTable({
  data,
  onView,
  onDelete,
  viewingPermissionName,
  deletingPermissionName,
}: PermissionsCatalogTableProps) {
  const [query, setQuery] = React.useState("");
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 20,
  });

  const filtered = React.useMemo(() => {
    return data.filter((row) => {
      if (!query.trim()) return true;
      return (
        matchesText(row.name, query) ||
        matchesText(row.label, query) ||
        matchesText(row.description, query)
      );
    });
  }, [data, query]);

  const columns = React.useMemo<ColumnDef<PermissionCatalogEntry>[]>(
    () => [
      {
        accessorKey: "name",
        header: "Permission",
        cell: ({ row }) => (
          <span className="font-mono text-sm">{row.original.name}</span>
        ),
      },
      {
        accessorKey: "label",
        header: "Label",
        cell: ({ row }) => <span className="text-sm">{row.original.label}</span>,
      },
      {
        accessorKey: "description",
        header: "Description",
        cell: ({ row }) => (
          <span className="line-clamp-2 text-muted-foreground text-sm">{row.original.description}</span>
        ),
      },
      {
        accessorKey: "usedByRoleCount",
        header: "Used by",
        cell: ({ row }) => (
          <span className="text-sm">{formatRoleCount(row.original.usedByRoleCount)}</span>
        ),
      },
      {
        accessorKey: "createdAt",
        header: "Created",
        cell: ({ row }) => (
          <span className="text-muted-foreground text-sm">
            {formatDisplayDate(row.original.createdAt)}
          </span>
        ),
      },
      {
        accessorKey: "updatedAt",
        header: "Updated",
        cell: ({ row }) => (
          <span className="text-muted-foreground text-sm">
            {formatDisplayDate(row.original.updatedAt)}
          </span>
        ),
      },
      {
        id: "actions",
        header: () => <span className="block w-full text-right">Actions</span>,
        cell: ({ row }) => (
          <RbacRowActions
            editHref={`/dashboard/admins/access/permissions/form?name=${encodeURIComponent(row.original.name)}`}
            viewLabel="View permission"
            editLabel="Edit permission"
            deleteLabel="Delete permission"
            onView={() => onView?.(row.original.name)}
            onDelete={() => onDelete?.(row.original.name)}
            viewDisabled={viewingPermissionName === row.original.name}
            deleteDisabled={deletingPermissionName === row.original.name}
          />
        ),
      },
    ],
    [deletingPermissionName, onDelete, onView, viewingPermissionName],
  );

  const table = useReactTable({
    data: filtered,
    columns,
    state: { pagination },
    onPaginationChange: setPagination,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getRowId: (row) => row.name,
  });

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-end gap-3">
        <div className="space-y-1">
          <Label htmlFor="perm-search" className="text-xs">
            Search
          </Label>
          <Input
            id="perm-search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Filter permissions…"
            className="h-9 w-[220px]"
          />
        </div>
      </div>
      <DataTableShell
        table={table}
        columnCount={columns.length}
        emptyMessage="No permissions match your filters."
      />
      <DataTablePagination
        table={table}
        totalRows={filtered.length}
        itemNoun="permission"
        idPrefix="permissions"
      />
    </div>
  );
}

function formatRoleCount(value: number) {
  return `${value} ${value === 1 ? "role" : "roles"}`;
}
