"use client";

import * as React from "react";
import { useSearchParams } from "next/navigation";
import { useUrlPagination } from "@/hooks/use-url-pagination";
import {
  ChevronLeft,
  ChevronRight,
  Plus,
  Pencil,
  Search,
  Trash2,
  CheckCircle2,
  X,
  Layers,
  ListChecks,
  Hash,
} from "lucide-react";
import {
  getApiEntityId,
  type CreatePermissionBody,
  type Permission as ApiPermission,
  type PermissionAction,
  type PermissionResource,
} from "@/api/permissions/types";
import {
  useCreatePermissionMutation,
  useUpdatePermissionMutation,
  useBulkDeletePermissionsMutation,
} from "@/api/rtk/permissions-api";
import { useSyncPermissionsCatalogFromQuery } from "@/hooks/use-sync-permissions-catalog-from-query";
import { useAppSelector } from "@/store/hooks";
import { selectPermissionsCatalogItems } from "@/store/slices/permissions-catalog-slice";
import { Can } from "@/components/providers/ability-provider";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { DeleteConfirmationAlert } from "@/components/ui/delete-confirmation-alert";
import { Loading } from "@/components/ui/loading";
import { NoDataFound } from "@/components/ui/no-data-found";
import {
  ReactSelect,
} from "@/components/ui/react-select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { Textarea } from "@/components/ui/textarea";
import { KPICard } from "@/components/ui/kpi-card";
import { formatDistanceToNow } from "date-fns";
import { useAuthToken } from "@/hooks/use-auth-token";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import {
  Combobox,
  ComboboxInput,
  ComboboxContent,
  ComboboxList,
  ComboboxItem,
  ComboboxEmpty,
} from "@/components/ui/combobox";

const DEFAULT_PAGE_SIZE = 10;
const ACTION_OPTIONS: PermissionAction[] = [
  "CREATE",
  "READ",
  "UPDATE",
  "DELETE",
  "MANAGE",
];

/** Catalog uses READ + MANAGE only (not CREATE/UPDATE/DELETE). */
const READ_MANAGE_RESOURCES = new Set<PermissionResource>(["SALES_TARGET"]);

/** Full catalog aligned with backend `Resource` enum (excluding deprecated QA_COMPLIANCE). */
const RESOURCE_OPTIONS: PermissionResource[] = [
  "ACTIVITY",
  "BDR_METRICS",
  "BULK_ASSIGN_LEAD",
  "BULK_EDIT_LEAD",
  "CLIENT_MEETING_VERIFICATION",
  "CUSTOMER",
  "DASHBOARD",
  "DEAL",
  "DEALS",
  "EXCEL_EXPORT",
  "EXCEL_IMPORT",
  "EXTRA_CONTENT",
  "DIVISION",
  "LEAD",
  "LEAD_HISTORY",
  "LOGIN_SESSION",
  "MARKETING",
  "PASSWORD_RESET_REQUEST",
  "PAYMENT_STRUCTURE",
  "PERMISSION",
  "PIPELINE",
  "REPORT",
  "ROLE",
  "SALES_TARGET",
  "TRANSACTION",
  "SETTINGS",
  "SUSPICIOUS_ACTIVITY",
  "TASK",
  "TEAM",
  "USER",
];

/** READ-only catalog resources. */
const READ_ONLY_RESOURCES = new Set<PermissionResource>([
  "ACTIVITY",
  "DASHBOARD",
  "LEAD_HISTORY",
  "SUSPICIOUS_ACTIVITY",
  "PASSWORD_RESET_REQUEST",
  "BDR_METRICS",
  "EXCEL_EXPORT",
  "TRANSACTION",
]);

/** UPDATE-only catalog resources. */
const UPDATE_ONLY_RESOURCES = new Set<PermissionResource>([
  "BULK_ASSIGN_LEAD",
  "BULK_EDIT_LEAD",
  "CLIENT_MEETING_VERIFICATION",
]);

/** CREATE-only catalog resources. */
const CREATE_ONLY_RESOURCES = new Set<PermissionResource>(["EXCEL_IMPORT"]);

function resourcesForPermissionAction(
  action: PermissionAction,
): PermissionResource[] {
  if (action === "MANAGE") {
    return ["SALES_TARGET"];
  }
  if (action === "UPDATE") {
    return RESOURCE_OPTIONS.filter(
      (r) =>
        !READ_ONLY_RESOURCES.has(r) &&
        !CREATE_ONLY_RESOURCES.has(r) &&
        !READ_MANAGE_RESOURCES.has(r),
    );
  }
  if (action === "READ") {
    return RESOURCE_OPTIONS.filter(
      (r) =>
        !CREATE_ONLY_RESOURCES.has(r) &&
        !UPDATE_ONLY_RESOURCES.has(r),
    );
  }
  if (action === "CREATE") {
    return RESOURCE_OPTIONS.filter(
      (r) =>
        !READ_ONLY_RESOURCES.has(r) &&
        !UPDATE_ONLY_RESOURCES.has(r) &&
        !READ_MANAGE_RESOURCES.has(r) &&
        r !== "LOGIN_SESSION",
    );
  }
  return RESOURCE_OPTIONS.filter(
    (r) =>
      !READ_ONLY_RESOURCES.has(r) &&
      !CREATE_ONLY_RESOURCES.has(r) &&
      !UPDATE_ONLY_RESOURCES.has(r) &&
      !READ_MANAGE_RESOURCES.has(r) &&
      r !== "LOGIN_SESSION",
  );
}

function actionsForPermissionResource(
  resource: PermissionResource,
): PermissionAction[] {
  if (READ_MANAGE_RESOURCES.has(resource)) {
    return ["READ", "MANAGE"];
  }
  if (READ_ONLY_RESOURCES.has(resource)) {
    return ["READ"];
  }
  if (CREATE_ONLY_RESOURCES.has(resource)) {
    return ["CREATE"];
  }
  if (UPDATE_ONLY_RESOURCES.has(resource)) {
    return ["UPDATE"];
  }
  if (resource === "LOGIN_SESSION") {
    return ["READ", "UPDATE"];
  }
  return ACTION_OPTIONS;
}

function sortedResourcesForPermissionAction(
  action: PermissionAction,
): PermissionResource[] {
  return resourcesForPermissionAction(action)
    .slice()
    .sort((a, b) =>
      formatResourceForUi(a).localeCompare(formatResourceForUi(b)),
    );
}

function formatResourceForUi(resource: PermissionResource): string {
  switch (resource) {
    case "LEAD":
      return "LEAD — Leads pipeline (see all leads)";
    case "DEALS":
      return "DEALS — Business deals / Deals board (see all)";
    case "EXCEL_IMPORT":
      return "EXCEL_IMPORT — Bulk import (Excel/JSON)";
    case "EXCEL_EXPORT":
      return "EXCEL_EXPORT — Export leads/deals (CSV/Excel)";
    case "SALES_TARGET":
      return "SALES_TARGET — Monthly targets (READ: lead-scoped view; MANAGE: org-wide edit, assign, export)";
    case "EXTRA_CONTENT":
      return "EXTRA_CONTENT";
    case "DIVISION":
      return "DIVISION — Org divisions and division heads";
    case "BULK_ASSIGN_LEAD":
      return "BULK_ASSIGN_LEAD — Bulk-assign leads (Team / AE / BDR / Contributors)";
    case "BULK_EDIT_LEAD":
      return "BULK_EDIT_LEAD — Bulk edit leads (status, brand, channel, team, owner, AE, …)";
    case "LOGIN_SESSION":
      return "LOGIN_SESSION — View and revoke login sessions";
    case "SUSPICIOUS_ACTIVITY":
      return "SUSPICIOUS_ACTIVITY — View suspicious security activity log";
    case "PASSWORD_RESET_REQUEST":
      return "PASSWORD_RESET_REQUEST — View administrator password reset requests";
    case "BDR_METRICS":
      return "BDR_METRICS — BDR funnel reports (assigned → SQL → meeting)";
    case "MARKETING":
      return "MARKETING — Campaigns, spend ledger, and marketing analytics";
    case "TRANSACTION":
      return "TRANSACTION — Payment transaction ledger (read-only)";
    case "CLIENT_MEETING_VERIFICATION":
      return "CLIENT_MEETING_VERIFICATION — Verify discovery meeting client attendance on leads";
    default:
      return resource;
  }
}

function permissionCode(p: Pick<ApiPermission, "resource" | "action">) {
  return `${p.resource.toLowerCase()}.${p.action.toLowerCase()}`;
}

function getErrorMessage(error: unknown, fallback: string) {
  if (
    error &&
    typeof error === "object" &&
    "data" in error &&
    error.data &&
    typeof error.data === "object" &&
    "message" in error.data
  ) {
    const message = (error.data as { message?: unknown }).message;
    if (typeof message === "string") return message;
    if (Array.isArray(message)) return message.filter(Boolean).join(", ");
  }

  if (error instanceof Error && error.message) return error.message;
  return fallback;
}

export default function PermissionsPage() {
  const { token: accessToken } = useAuthToken();
  const searchParams = useSearchParams();
  const { page, setPage, limit, setLimit } = useUrlPagination(DEFAULT_PAGE_SIZE);
  const [search, setSearch] = React.useState(searchParams.get("search") || "");
  const [categoryFilter, setCategoryFilter] = React.useState(
    searchParams.get("resource") || "all"
  );
  const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
  const [editingPermission, setEditingPermission] = React.useState<ApiPermission | null>(null);
  const [formAction, setFormAction] = React.useState<PermissionAction>("CREATE");
  const [formResource, setFormResource] = React.useState<PermissionResource>("USER");
  const [formDescription, setFormDescription] = React.useState("");
  const [selectedIds, setSelectedIds] = React.useState<string[]>([]);
  const [isBulkDeleteDialogOpen, setIsBulkDeleteDialogOpen] = React.useState(false);

  const permissions = useAppSelector(selectPermissionsCatalogItems);
  const { isLoading, isUninitialized, error } = useSyncPermissionsCatalogFromQuery(!accessToken);
  const [createPermission, { isLoading: isCreatingPermission }] = useCreatePermissionMutation();
  const [updatePermission, { isLoading: isUpdatingPermission }] = useUpdatePermissionMutation();
  const [bulkDeletePermissions, { isLoading: isBulkDeleting }] = useBulkDeletePermissionsMutation();

  const waitingForToken = !accessToken && isUninitialized;

  const filteredPermissions = React.useMemo(() => {
    const query = search.trim().toLowerCase();

    return permissions.filter((permission) => {
      const matchesSearch =
        query === "" ||
        [permissionCode(permission), permission.resource, permission.action, permission.description ?? ""]
          .join(" ")
          .toLowerCase()
          .includes(query);

      const matchesCategory =
        categoryFilter === "all" || categoryFilter === permission.resource;

      return matchesSearch && matchesCategory;
    });
  }, [permissions, search, categoryFilter]);

  const pageLimitOptions = React.useMemo(
    () => [
      { value: "10", label: "10 / page" },
      { value: "20", label: "20 / page" },
      { value: "50", label: "50 / page" },
    ],
    [],
  );

  const permissionActionOptions = React.useMemo(
    () =>
      actionsForPermissionResource(formResource).map((action) => ({
        value: action,
        label: action,
      })),
    [formResource],
  );

  const categories = React.useMemo(() => {
    const set = new Set(permissions.map((permission) => permission.resource));
    return Array.from(set).sort();
  }, [permissions]);

  const total = filteredPermissions.length;
  const totalPages = Math.max(1, Math.ceil(total / limit));
  const paginatedPermissions = React.useMemo(
    () => filteredPermissions.slice((page - 1) * limit, page * limit),
    [filteredPermissions, page, limit]
  );

  React.useEffect(() => {
    if (page > totalPages) {
      setPage(1);
    }
  }, [page, setPage, totalPages]);

  const resetCreateForm = React.useCallback(() => {
    setFormAction("CREATE");
    setFormResource("USER");
    setFormDescription("");
  }, []);

  const createDialogResources = React.useMemo(
    () => sortedResourcesForPermissionAction(formAction),
    [formAction],
  );

  React.useEffect(() => {
    const allowedActions = actionsForPermissionResource(formResource);
    if (!allowedActions.includes(formAction)) {
      setFormAction(allowedActions[0] ?? "READ");
    }
  }, [formResource, formAction]);

  React.useEffect(() => {
    const allowed = resourcesForPermissionAction(formAction);
    if (!allowed.includes(formResource)) {
      setFormResource(
        sortedResourcesForPermissionAction(formAction)[0] ?? "USER",
      );
    }
  }, [formAction, formResource]);

  const handleCreateDialogChange = (open: boolean) => {
    setIsCreateDialogOpen(open);
    if (!open) {
      resetCreateForm();
    }
  };

  const openEditDialog = (permission: ApiPermission) => {
    setIsCreateDialogOpen(false);
    setEditingPermission(permission);
    setFormAction(permission.action);
    setFormResource(permission.resource);
    setFormDescription(permission.description ?? "");
  };

  const handleEditDialogChange = (open: boolean) => {
    if (!open) {
      setEditingPermission(null);
      resetCreateForm();
    }
  };

  const handleCreatePermission = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const payload: CreatePermissionBody = {
      action: formAction,
      resource: formResource,
      description: formDescription.trim() || undefined,
    };

    try {
      const created = await createPermission(payload).unwrap();
      toast.success(`Permission ${permissionCode(created)} created`);
      handleCreateDialogChange(false);
    } catch (mutationError) {
      toast.error(getErrorMessage(mutationError, "Failed to create permission"));
    }
  };

  const handleUpdatePermission = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const id = editingPermission ? getApiEntityId(editingPermission) : undefined;
    if (!id) {
      toast.error("Permission id is missing");
      return;
    }

    const payload: CreatePermissionBody = {
      action: formAction,
      resource: formResource,
      description: formDescription.trim() || undefined,
    };

    try {
      const updated = await updatePermission({ id, body: payload }).unwrap();
      toast.success(`Permission ${permissionCode(updated)} updated`);
      handleEditDialogChange(false);
    } catch (mutationError) {
      toast.error(getErrorMessage(mutationError, "Failed to update permission"));
    }
  };

  const handleSearchChange = async (value: string) => {
    await setPage(1);
    await setSearch(value);
  };

  const handleCategoryChange = async (value: string) => {
    await setPage(1);
    await setCategoryFilter(value);
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const ids = paginatedPermissions
        .map((p) => getApiEntityId(p))
        .filter((id): id is string => Boolean(id));
      setSelectedIds(ids);
    } else {
      setSelectedIds([]);
    }
  };

  const handleSelectRow = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedIds((prev) => [...prev, id]);
    } else {
      setSelectedIds((prev) => prev.filter((i) => i !== id));
    }
  };

  const handleBulkDelete = async () => {
    try {
      await bulkDeletePermissions(selectedIds).unwrap();
      toast.success(`${selectedIds.length} permissions deleted successfully`);
      setSelectedIds([]);
      setIsBulkDeleteDialogOpen(false);
    } catch (err) {
      toast.error(getErrorMessage(err, "Failed to delete permissions"));
      throw err;
    }
  };

  if (waitingForToken) {
    return (
      <div className="flex flex-col h-full gap-5 p-4 sm:p-6 md:p-8 animate-in fade-in duration-500 overflow-y-auto scrollbar-themed">
        <Loading message="Loading..." className="py-24" />
      </div>
    );
  }

  const permissionsFetchFailed = Boolean(error) && permissions.length === 0;

  if (permissionsFetchFailed) {
    return (
      <div className="flex flex-col h-full gap-5 p-4 sm:p-6 md:p-8 animate-in fade-in duration-500 overflow-y-auto scrollbar-themed">
        <div className="rounded-[20px] border border-[#eaecf0] bg-white/70 p-8 shadow-sm">
          <p className="text-sm font-medium text-destructive">
            Failed to load permissions. You may not have access.
          </p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="flex flex-col h-full gap-5 p-4 sm:p-6 md:p-8 animate-in fade-in duration-500 overflow-y-auto scrollbar-themed">
        <div className="flex flex-col flex-1 min-h-0 gap-5">
          <div className="flex flex-col gap-6 border-b border-border/60 pb-8 shrink-0 md:flex-row md:items-start md:justify-between">
            <div className="flex flex-col gap-1">
              <h1 className="text-2xl font-extrabold tracking-tight text-[#101828] font-['Lexend'] sm:text-3xl">
                Permission Management
              </h1>
              <p className="text-sm font-normal text-[#475467]">
                Manage system permission codes and capabilities.
              </p>
            </div>
          </div>

          <div className="mt-0 flex flex-col gap-6 pb-12 focus-visible:outline-none">
            <div className="grid shrink-0 grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
              <KPICard
                label="Total codes"
                value={permissions.length.toString()}
                subtext="capability definitions"
                icon={<ListChecks size={20} className="text-accent" />}
                className="rounded-2xl border-white/60 bg-white/40 shadow-sm backdrop-blur-sm"
              />
              <KPICard
                label="Resources"
                value={categories.length.toString()}
                subtext="distinct modules"
                icon={<Layers size={20} className="text-accent" />}
                className="rounded-2xl border-white/60 bg-white/40 shadow-sm backdrop-blur-sm"
              />
              <KPICard
                label="Matching filter"
                value={total.toString()}
                subtext="rows in current view"
                icon={<Hash size={20} className="text-accent" />}
                className="rounded-2xl border-white/60 bg-white/40 shadow-sm backdrop-blur-sm sm:col-span-2 xl:col-span-1"
              />
            </div>

            <div className="flex flex-wrap items-center justify-end gap-3">
              <Can action="update" subject="permission">
                <Button
                  size="sm"
                  onClick={() => setIsCreateDialogOpen(true)}
                  className="h-10 gap-2 rounded-xl bg-accent px-5 font-semibold shadow-sm transition-all hover:bg-accent/90"
                >
                  <Plus size={18} className="stroke-[2px]" /> New permission code
                </Button>
              </Can>
            </div>

            <div className="flex shrink-0 flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-center">
              <div className="relative min-w-0 flex-1 sm:min-w-[280px]">
                <Search
                  size={16}
                  className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#667085] stroke-[2px]"
                />
                <Input
                  type="search"
                  placeholder="Search by resource, action, or code…"
                  className="h-10 rounded-xl border-[#d0d5dd] bg-white pl-10 pr-4 text-[14px] font-medium shadow-sm transition-all focus:ring-accent/20"
                  value={search}
                  onChange={(event) => void handleSearchChange(event.target.value)}
                  aria-label="Search permissions"
                />
              </div>
              <div className="w-full min-w-0 sm:w-[200px]">
                <Combobox
                  value={categoryFilter}
                  onValueChange={(val) => void handleCategoryChange(val as string)}
                >
                  <ComboboxInput
                    placeholder="Resource filter"
                    className="h-10 rounded-xl border-[#d0d5dd] bg-white text-[14px] font-medium shadow-sm transition-all focus:ring-accent/20"
                  />
                  <ComboboxContent>
                    <ComboboxList>
                      <ComboboxItem value="all" className="text-[12px] font-medium">
                        All Resources
                      </ComboboxItem>
                      {categories.map((category) => (
                        <ComboboxItem key={category} value={category} className="text-[12px] font-medium">
                          {formatResourceForUi(category as PermissionResource)}
                        </ComboboxItem>
                      ))}
                    </ComboboxList>
                    <ComboboxEmpty className="text-[12px]">No resource found</ComboboxEmpty>
                  </ComboboxContent>
                </Combobox>
              </div>
            </div>

            <div className="flex shrink-0 flex-col space-y-6">
              <div className="overflow-hidden rounded-[20px] border border-[#eaecf0] bg-white/70 shadow-sm backdrop-blur-md">
                <div className="scrollbar-themed overflow-x-auto">
                  {(isLoading || isUninitialized) && permissions.length === 0 ? (
                    <Loading layout="section" message="Loading permissions…" className="py-24" />
                  ) : (
                    <Table variant="transparent">
                      <TableHeader>
                        <TableRow className="border-b border-[#eaecf0] bg-[#f9fafb]/80 hover:bg-transparent">
                          <TableHead className="w-[50px] pl-4">
                            <Checkbox
                              checked={
                                paginatedPermissions.length > 0 &&
                                paginatedPermissions.every((p) =>
                                  selectedIds.includes(getApiEntityId(p) ?? "")
                                )
                              }
                              onCheckedChange={(checked) => handleSelectAll(!!checked)}
                            />
                          </TableHead>
                          <TableHead className="w-[180px] py-4 font-bold text-[#475467]">
                            <div className="px-1 text-[11px] font-bold uppercase tracking-wider">Resource</div>
                          </TableHead>
                          <TableHead className="w-[180px] py-4 font-bold text-[#475467]">
                            <div className="text-[11px] font-bold uppercase tracking-wider">Action</div>
                          </TableHead>
                          <TableHead className="w-[220px] py-4 font-bold text-[#475467]">
                            <div className="text-[11px] font-bold uppercase tracking-wider">Code</div>
                          </TableHead>
                          <TableHead className="min-w-0 flex-1 py-4 font-bold text-[#475467]">
                            <div className="text-[11px] font-bold uppercase tracking-wider">Description</div>
                          </TableHead>
                          <TableHead className="w-[140px] py-4 font-bold text-[#475467]">
                            <div className="text-[11px] font-bold uppercase tracking-wider">Created At</div>
                          </TableHead>
                          <TableHead className="w-[140px] py-4 font-bold text-[#475467]">
                            <div className="text-[11px] font-bold uppercase tracking-wider">Updated At</div>
                          </TableHead>
                          <TableHead className="w-[100px] py-4 text-right font-bold text-[#475467]">
                            <div className="px-2 text-[11px] font-bold uppercase tracking-wider">Actions</div>
                          </TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {paginatedPermissions.length > 0 ? (
                          paginatedPermissions.map((permission) => {
                            const id = getApiEntityId(permission) ?? permissionCode(permission);
                            return (
                              <TableRow
                                key={id}
                                className={cn(
                                  "group border-b border-[#eaecf0] transition-colors hover:bg-[#f9fafb]",
                                  selectedIds.includes(getApiEntityId(permission) ?? "") && "bg-accent/[0.06]"
                                )}
                              >
                                <TableCell className="py-4 pl-4">
                                  <Checkbox
                                    checked={selectedIds.includes(getApiEntityId(permission) ?? "")}
                                    onCheckedChange={(checked) =>
                                      handleSelectRow(getApiEntityId(permission) ?? "", !!checked)
                                    }
                                  />
                                </TableCell>
                                <TableCell className="py-4">
                                  <div className="flex items-center gap-2">
                                    <div className="size-1.5 shrink-0 rounded-full bg-accent" />
                                    <span className="text-[10px] font-extrabold uppercase tracking-widest text-accent">
                                      {formatResourceForUi(permission.resource)}
                                    </span>
                                  </div>
                                </TableCell>
                                <TableCell className="py-4">
                                  <span className="text-[14px] font-bold text-[#101828] font-['Lexend']">
                                    {permission.action}
                                  </span>
                                </TableCell>
                                <TableCell className="py-4">
                                  <code className="rounded-md border border-accent/10 bg-[#f9fafb] px-2 py-0.5 font-mono text-[11px] font-bold text-accent">
                                    {permissionCode(permission)}
                                  </code>
                                </TableCell>
                                <TableCell className="py-4">
                                  <span className="text-[13px] font-medium text-[#475467]">
                                    {permission.description?.trim() || "—"}
                                  </span>
                                </TableCell>
                                <TableCell className="py-4">
                                  <span className="text-[13px] font-medium text-[#475467]">
                                    {permission.createdAt ? new Date(permission.createdAt).toLocaleDateString() : "—"}
                                  </span>
                                </TableCell>
                                <TableCell className="py-4">
                                  <span className="text-[13px] font-medium text-[#475467]">
                                    {permission.updatedAt ? formatDistanceToNow(new Date(permission.updatedAt), { addSuffix: true }) : "—"}
                                  </span>
                                </TableCell>
                                <TableCell className="py-4 text-right">
                                  <Can action="update" subject="permission">
                                    <Button
                                      type="button"
                                      variant="ghost"
                                      size="sm"
                                      className="h-8 gap-1.5 rounded-lg px-2.5 text-[12px] font-semibold text-[#475467] hover:bg-accent/10 hover:text-accent"
                                      onClick={() => openEditDialog(permission)}
                                      aria-label={`Edit ${permissionCode(permission)}`}
                                    >
                                      <Pencil size={14} />
                                      Edit
                                    </Button>
                                  </Can>
                                </TableCell>
                              </TableRow>
                            );
                          })
                        ) : (
                          <TableRow>
                            <TableCell colSpan={8} className="p-0">
                              <NoDataFound
                                message="No permissions found"
                                description="Try adjusting your search or filters."
                              />
                            </TableCell>
                          </TableRow>
                        )}
                      </TableBody>
                    </Table>
                  )}

                  {total > 0 && (
                    <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[#eaecf0] px-4 py-3">
                      <div className="flex items-center gap-3">
                        <span className="text-[12px] font-medium text-[#667085]">
                          Showing {(page - 1) * limit + 1}-{Math.min(page * limit, total)} of {total}
                        </span>
                        <ReactSelect
                          value={String(limit)}
                          onValueChange={(value) => {
                            setLimit(Number.parseInt(value, 10));
                            setPage(1);
                          }}
                          options={pageLimitOptions}
                          triggerClassName="h-9 w-[100px] rounded-lg text-[12px] border-[#d0d5dd]"
                        />
                      </div>
                      {totalPages > 1 && (
                        <Pagination className="mx-0 w-auto">
                          <PaginationContent>
                            <PaginationItem>
                              <PaginationPrevious
                                href="#"
                                onClick={(e) => {
                                  e.preventDefault();
                                  if (page > 1) setPage((current) => Math.max(1, current - 1));
                                }}
                                className={page <= 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                              />
                            </PaginationItem>
                            <PaginationItem>
                              <span className="px-4 text-[12px] font-bold text-[#344054]">
                                {page} / {totalPages}
                              </span>
                            </PaginationItem>
                            <PaginationItem>
                              <PaginationNext
                                href="#"
                                onClick={(e) => {
                                  e.preventDefault();
                                  if (page < totalPages) setPage((current) => Math.min(totalPages, current + 1));
                                }}
                                className={page >= totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
                              />
                            </PaginationItem>
                          </PaginationContent>
                        </Pagination>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <Dialog open={Boolean(editingPermission)} onOpenChange={handleEditDialogChange}>
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle className="font-['Lexend']">Edit Permission Code</DialogTitle>
            <DialogDescription>
              Update action, resource, or description for this capability code.
            </DialogDescription>
          </DialogHeader>

          <form className="grid gap-4" onSubmit={handleUpdatePermission}>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="edit-permission-action">Action</Label>
                <ReactSelect
                  id="edit-permission-action"
                  value={formAction}
                  onValueChange={(value) =>
                    setFormAction(value as PermissionAction)
                  }
                  options={permissionActionOptions}
                  placeholder="Select action"
                />
              </div>

              <div className="grid gap-2">
                <Label htmlFor="edit-permission-resource">Resource</Label>
                <Combobox
                  key={`edit-${formAction}`}
                  items={createDialogResources}
                  value={formResource}
                  itemToStringLabel={(resource) =>
                    formatResourceForUi(resource as PermissionResource)
                  }
                  onValueChange={(value) => {
                    if (value) {
                      setFormResource(value as PermissionResource);
                    }
                  }}
                >
                  <ComboboxInput
                    id="edit-permission-resource"
                    placeholder="Search or select resource…"
                    className="h-10 w-full rounded-xl border-[#d0d5dd] bg-white text-[14px] font-medium shadow-sm transition-all focus:ring-accent/20"
                  />
                  <ComboboxContent className="max-h-[min(320px,70vh)]">
                    <ComboboxList>
                      {(resource) => (
                        <ComboboxItem
                          key={resource}
                          value={resource}
                          className="text-[12px] font-medium"
                        >
                          {formatResourceForUi(resource as PermissionResource)}
                        </ComboboxItem>
                      )}
                    </ComboboxList>
                    <ComboboxEmpty className="text-[12px]">
                      No matching resource
                    </ComboboxEmpty>
                  </ComboboxContent>
                </Combobox>
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="edit-permission-code-preview">Code preview</Label>
              <Input
                id="edit-permission-code-preview"
                value={permissionCode({ resource: formResource, action: formAction })}
                readOnly
                className="font-mono text-[12px] bg-muted/40"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="edit-permission-description">Description</Label>
              <Textarea
                id="edit-permission-description"
                value={formDescription}
                onChange={(event) => setFormDescription(event.target.value)}
                placeholder="Optional note about what this permission grants"
                rows={4}
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => handleEditDialogChange(false)}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isUpdatingPermission}>
                {isUpdatingPermission ? "Saving..." : "Save changes"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={isCreateDialogOpen} onOpenChange={handleCreateDialogChange}>
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle className="font-['Lexend']">Create Permission Code</DialogTitle>
            <DialogDescription>
              Define a new action and resource pair for the permission catalog.
            </DialogDescription>
          </DialogHeader>

          <form className="grid gap-4" onSubmit={handleCreatePermission}>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="permission-action">Action</Label>
                <ReactSelect
                  id="permission-action"
                  value={formAction}
                  onValueChange={(value) =>
                    setFormAction(value as PermissionAction)
                  }
                  options={permissionActionOptions}
                  placeholder="Select action"
                />
              </div>

              <div className="grid gap-2">
                <Label htmlFor="permission-resource">Resource</Label>
                <Combobox
                  key={formAction}
                  items={createDialogResources}
                  value={formResource}
                  itemToStringLabel={(resource) =>
                    formatResourceForUi(resource as PermissionResource)
                  }
                  onValueChange={(value) => {
                    if (value) {
                      setFormResource(value as PermissionResource);
                    }
                  }}
                >
                  <ComboboxInput
                    id="permission-resource"
                    placeholder="Search or select resource…"
                    className="h-10 w-full rounded-xl border-[#d0d5dd] bg-white text-[14px] font-medium shadow-sm transition-all focus:ring-accent/20"
                  />
                  <ComboboxContent className="max-h-[min(320px,70vh)]">
                    <ComboboxList>
                      {(resource) => (
                        <ComboboxItem
                          key={resource}
                          value={resource}
                          className="text-[12px] font-medium"
                        >
                          {formatResourceForUi(resource as PermissionResource)}
                        </ComboboxItem>
                      )}
                    </ComboboxList>
                    <ComboboxEmpty className="text-[12px]">
                      No matching resource
                    </ComboboxEmpty>
                  </ComboboxContent>
                </Combobox>
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="permission-code-preview">Code preview</Label>
              <Input
                id="permission-code-preview"
                value={permissionCode({ resource: formResource, action: formAction })}
                readOnly
                className="font-mono text-[12px] bg-muted/40"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="permission-description">Description</Label>
              <Textarea
                id="permission-description"
                value={formDescription}
                onChange={(event) => setFormDescription(event.target.value)}
                placeholder="Optional note about what this permission grants"
                rows={4}
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => handleCreateDialogChange(false)}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isCreatingPermission}>
                {isCreatingPermission ? "Creating..." : "Create Code"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <DeleteConfirmationAlert
        open={isBulkDeleteDialogOpen}
        onOpenChange={setIsBulkDeleteDialogOpen}
        onConfirm={handleBulkDelete}
        title="Delete Permissions"
        description={`Are you sure you want to delete ${selectedIds.length} selected permissions? This action cannot be undone.`}
        confirmText="Delete Permissions"
        isLoading={isBulkDeleting}
      />

      {selectedIds.length > 0 && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-bottom-4 duration-300">
          <div className="bg-white dark:bg-gray-900 border border-border shadow-2xl rounded-2xl px-4 py-3 flex items-center gap-6 min-w-[400px]">
            <div className="flex items-center gap-3 border-r border-border pr-6">
              <div className="size-8 rounded-xl bg-accent/10 flex items-center justify-center text-accent">
                <CheckCircle2 size={18} />
              </div>
              <div className="flex flex-col">
                <span className="text-[13px] font-bold text-gray-900 dark:text-gray-100 line-height-none">
                  {selectedIds.length} Selected
                </span>
                <span className="text-[11px] text-gray-500 font-medium">
                  Bulk actions available
                </span>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <Button
                variant="destructive"
                size="sm"
                className="h-9 rounded-xl px-4 text-[12px] font-bold shadow-md shadow-red-100"
                onClick={() => setIsBulkDeleteDialogOpen(true)}
              >
                <Trash2 size={14} className="mr-2" />
                Remove Permissions
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="h-9 rounded-xl px-4 text-[12px] font-bold text-gray-500 hover:text-gray-900"
                onClick={() => setSelectedIds([])}
              >
                <X size={14} className="mr-2" />
                Clear Selection
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
