"use client";

import * as React from "react";

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

import {
  DataTablePagination,
  DataTableShell,
} from "@/app/dashboard/_components/data-table";
import { RbacRowActions } from "@/components/admins/rbac/rbac-row-actions";
import { Button } from "@/components/ui/button";

import { RoleBadge } from "./role-badge";
import { RoleCapabilityBadge } from "./role-capability-badge";
import type { Role } from "./types";

function buildColumns({
  onDelete,
  onView,
}: {
  onDelete: (role: Role) => void;
  onView: (role: Role) => void;
}): ColumnDef<Role>[] {
  return [
    {
      accessorKey: "name",
      header: "Name",
      cell: ({ row }) => (
        <div className="flex flex-wrap items-center gap-2">
          <Link
            href={`/dashboard/admins/access/roles/${row.original.id}`}
            className="font-medium font-mono text-primary text-sm hover:underline"
          >
            {row.original.name}
          </Link>
          {row.original.capability ? (
            <RoleCapabilityBadge capability={row.original.capability} />
          ) : null}
        </div>
      ),
    },
    {
      accessorKey: "type",
      header: "Type",
      cell: ({ row }) => <RoleBadge type={row.original.type} />,
    },
    {
      accessorKey: "permissions",
      header: "Permissions",
      cell: ({ row }) => (
        <span className="text-sm">
          {row.original.permissionCount ?? row.original.permissions.length}
        </span>
      ),
    },
    {
      id: "assigned",
      header: "Assigned",
      cell: ({ row }) => (
        <span className="text-muted-foreground text-sm">
          {row.original.assignedStaffCount} staff · {row.original.assignedCustomerCount} customers
        </span>
      ),
    },
    {
      accessorKey: "description",
      header: "Description",
      cell: ({ row }) => (
        <span className="line-clamp-1 text-muted-foreground text-sm">{row.original.description}</span>
      ),
    },
    {
      id: "actions",
      header: () => <span className="block w-full text-right">Actions</span>,
      cell: ({ row }) => {
        const role = row.original;
        return (
          <RbacRowActions
            editHref={`/dashboard/admins/access/roles/${role.id}`}
            viewLabel="View role"
            editLabel="Edit role"
            deleteLabel="Delete role"
            onView={() => onView(role)}
            onDelete={() => onDelete(role)}
          />
        );
      },
    },
  ];
}

export function RolesTable({
  data,
  onDelete,
  onView,
}: {
  data: Role[];
  onDelete: (role: Role) => void;
  onView: (role: Role) => void;
}) {
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 20,
  });

  const columns = React.useMemo(
    () => buildColumns({ onDelete, onView }),
    [onDelete, onView],
  );

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

  return (
    <div className="space-y-4">
      <DataTableShell
        table={table}
        columnCount={columns.length}
        emptyMessage="No roles found."
      />
      <DataTablePagination
        table={table}
        totalRows={data.length}
        itemNoun="role"
        idPrefix="roles"
      />
    </div>
  );
}

export function RolesHeaderActions() {
  return (
    <Button asChild size="sm">
      <Link href="/dashboard/admins/access/roles/create">
        <Plus className="size-4" />
        Create role
      </Link>
    </Button>
  );
}
