import React from 'react'

import { type HoverHintReason, ReasonHoverHint } from 'dbaas/components/HoverHint/ReasonHoverHint'

import { type BasicAccessCheckProps } from '../core/access-check-shared'

import { useAccessDeniedHintReason } from './use-access-denied-hint-reason'

type AccessDeniedHoverHintChildrenRenderFn = (params: { accessible: boolean }) => React.ReactNode

interface AccessDeniedHoverHintProps extends BasicAccessCheckProps {
  /**
   * Customize hover card display (e.g., positioning, styling).
   *
   * Note: `when` and `content` are auto-managed based on access check result.
   */
  reason?: Partial<Omit<HoverHintReason, 'when' | 'content'>>
  /**
   * Target element.
   *
   * **Use render-prop when you want to control `disabled` state based on access:**
   * ```tsx
   * {({ accessible }) => <Button disabled={!accessible}>...</Button>}
   * ```
   *
   * Use static children when you only want to show hints without controlling state.
   */
  children: React.ReactNode | AccessDeniedHoverHintChildrenRenderFn
}

/**
 * Hover hint component that shows "Access Denied" message when user lacks permissions.
 *
 * ⚠️ **IMPORTANT**: This component does **NOT** automatically disable children.
 * You **MUST** manually handle the disabled state using the render-prop pattern.
 *
 * This is a specialized wrapper around `ReasonHoverHint` for access control scenarios.
 *
 * @example
 * // ✅ Correct: Using render-prop to control disabled state
 * <AccessDeniedHoverHint id="OrgUsersAction">
 *   {({ accessible }) => (
 *     <Button disabled={!accessible} onClick={handleAddUser}>
 *       Add User
 *     </Button>
 *   )}
 * </AccessDeniedHoverHint>
 *
 * @example
 * // ❌ Wrong: Button will be clickable even when access is denied
 * <AccessDeniedHoverHint id="OrgUsersAction">
 *   <Button onClick={handleAddUser}>Add User</Button>
 * </AccessDeniedHoverHint>
 *
 * @example
 * // ✅ With custom scope (cross-resource check)
 * <AccessDeniedHoverHint
 *   id="ClusterDelete"
 *   scopeProps={{ tidbId: anotherCluster.id }}
 * >
 *   {({ accessible }) => (
 *     <Button
 *       disabled={!accessible}
 *       color="red"
 *       onClick={() => deleteCluster(anotherCluster.id)}
 *     >
 *       Delete
 *     </Button>
 *   )}
 * </AccessDeniedHoverHint>
 */
export const AccessDeniedHoverHint = ({
  id,
  scopeProps,
  reason: reasonOverrides,
  children
}: AccessDeniedHoverHintProps) => {
  const { accessible, reason } = useAccessDeniedHintReason({
    id,
    scopeProps,
    reason: reasonOverrides
  })
  const renderedChildren = typeof children === 'function' ? children({ accessible }) : children

  return <ReasonHoverHint reasons={[reason]}>{renderedChildren}</ReasonHoverHint>
}
