'use client';

import { forwardRef } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react';

import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';

export interface ChatHeaderActionButtonProps
  extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children'> {
  /** Icon (required). */
  icon: ReactNode;
  /** Accessible label — also drives the hover/focus tooltip. */
  ariaLabel: string;
  /**
   * Tooltip copy. Defaults to `ariaLabel`. Pass to show a friendlier
   * label than the (sometimes terse) aria string. Set `false` to opt
   * out of the floating tooltip entirely.
   */
  tooltip?: ReactNode | false;
  /** Optional unread / status badge — small number on top-right. */
  badge?: number;
  /** Mark as destructive — uses destructive hover tokens. */
  destructive?: boolean;
  /** Optional visual loading state (e.g. while reset is in flight). */
  loading?: boolean;
}

/**
 * Compact icon button for the chat header actions slot.
 *
 * Standard chrome: 28×28 ghost button, hover bg-accent, focus ring, optional
 * destructive variant, optional numeric badge for unread / pending.
 *
 * Shows a floating tooltip (ui-core `<Tooltip>`) on hover *and* keyboard
 * focus; falls back to the native `title` attribute as well.
 *
 * @example
 * ```tsx
 * <ChatHeader
 *   title="Assistant"
 *   onClose={close}
 *   actions={
 *     <>
 *       <ChatHeaderActionButton
 *         icon={<RotateCcw className="h-3.5 w-3.5" />}
 *         ariaLabel="Clear context"
 *         onClick={handleReset}
 *         loading={isResetting}
 *       />
 *       <ChatHeaderActionButton
 *         icon={<Settings className="h-3.5 w-3.5" />}
 *         ariaLabel="Settings"
 *         onClick={openSettings}
 *       />
 *     </>
 *   }
 * />
 * ```
 */
export const ChatHeaderActionButton = forwardRef<HTMLButtonElement, ChatHeaderActionButtonProps>(
  function ChatHeaderActionButton(
    { icon, ariaLabel, tooltip, badge, destructive, loading, disabled, className, ...rest },
    ref,
  ) {
    const button = (
      <button
        ref={ref}
        type="button"
        aria-label={ariaLabel}
        disabled={disabled || loading}
        className={cn(
          'relative inline-flex h-7 w-7 items-center justify-center rounded-md',
          'text-muted-foreground transition-colors',
          'hover:bg-accent hover:text-foreground',
          'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring',
          'disabled:opacity-50 disabled:cursor-not-allowed',
          destructive && 'hover:bg-destructive/15 hover:text-destructive',
          loading && 'animate-pulse',
          className,
        )}
        {...rest}
      >
        {icon}
        {badge !== undefined && (
          <span
            aria-hidden="true"
            className="absolute -right-0.5 -top-0.5 inline-flex min-w-[14px] h-[14px] items-center justify-center rounded-full bg-destructive px-1 text-[9px] font-semibold leading-none text-destructive-foreground ring-2 ring-background"
          >
            {badge > 9 ? '9+' : badge}
          </span>
        )}
      </button>
    );

    // Opted out — render the button without any tooltip.
    if (tooltip === false) return button;

    // Floating tooltip on hover *and* keyboard focus.
    // Host app mounts <UiProviders> (which includes TooltipProvider).
    const tooltipLabel = tooltip ?? ariaLabel;
    return (
      <Tooltip>
        <TooltipTrigger asChild>{button}</TooltipTrigger>
        {/* Tooltip portals to <body> in ui-core's anchored-overlay tier,
            already above the dock — no z-index override needed. */}
        <TooltipContent side="bottom">{tooltipLabel}</TooltipContent>
      </Tooltip>
    );
  },
);
