// permissions.tsx
import type { UseFormSetValue, Path, FieldValues } from "react-hook-form";
import { GLOBAL_ACTIONS_META, ActionKey } from "@/constants/actionsMeta";
import { ACTIONS } from "@/constants/constants";
import type { Action, Resource } from "@/types/permissions";
import type { ActionItem } from "@/types/table";
import { usePermissions } from "@/lib/permissions";

type ActionKeys = keyof typeof ACTIONS;

// Simple mapping of UI actions to permissions
const ACTION_PERMISSION_MAP: Record<ActionKey, Action> = {
  VIEW: "read",
  EDIT: "update",
  DELETE: "delete",
};

// Create action items from keys
function createActions<T extends FieldValues, R>(
  actionKeys: ActionKeys[],
  setValue: UseFormSetValue<T>,
  getId: (row: R) => string,
  resource?: Resource,
  canDo?: (resource: Resource, action: Action) => boolean
): ActionItem[] {
  return actionKeys
    .filter((key) => {
      // If no resource or canDo function, allow all actions
      if (!resource || !canDo) return true;

      const requiredAction =
        ACTION_PERMISSION_MAP[key as ActionKey] || "update";
      return canDo(resource, requiredAction);
    })
    .map((key) => {
      const meta = GLOBAL_ACTIONS_META[key as ActionKey];
      const actionValue = ACTIONS[key];

      return {
        ...meta,
        onClick: (item: any, event?: React.MouseEvent) => {
          event?.stopPropagation();

          setValue("selectedId" as Path<T>, getId(item) as any);
          setValue("selectedAction" as Path<T>, actionValue as any);
          setValue("actionDialogOpen" as Path<T>, true as any);
        },
      };
    });
}

// Hook for static actions (same for all rows)
export function useActions<T extends FieldValues, R>(
  actionKeys: ActionKeys[],
  setValue: UseFormSetValue<T>,
  getId: (row: R) => string,
  resource?: Resource
): ActionItem[] {
  const { canDo } = usePermissions();

  return createActions(actionKeys, setValue, getId, resource, canDo);
}

// Hook for dynamic actions (different per row)
export function useRowActions<
  T extends Record<string, unknown>,
  F extends FieldValues
>(
  getKeysForRow: (row: T) => ActionKeys[],
  setValue: UseFormSetValue<F>,
  getId: (row: T) => string,
  resource?: Resource
): (row: T) => ActionItem[] {
  const { canDo } = usePermissions();

  return (row: T) => {
    const actionKeys = getKeysForRow(row);
    return createActions(actionKeys, setValue, getId, resource, canDo);
  };
}
