'use client';

import { memo } from 'react';
import { Copy, Pencil, RefreshCw, Trash } from 'lucide-react';

import { cn } from '@djangocfg/ui-core/lib';

import { useChatDestructiveStyles } from '../styles';
import type { ChatRole } from '../types';

export interface MessageActionsProps {
  role: ChatRole;
  onCopy?: () => void;
  onRegenerate?: () => void;
  onEdit?: () => void;
  onDelete?: () => void;
  hideOn?: Array<ChatRole>;
  className?: string;
}

/**
 * MessageActions — copy/regenerate/edit/delete buttons for a chat bubble.
 *
 * Memoised: re-renders only when `role`, `hideOn`, `className` or
 * any handler reference changes. Event handlers are compared by
 * reference — callers should stabilise them with useCallback.
 */
function MessageActionsRaw({
  role,
  onCopy,
  onRegenerate,
  onEdit,
  onDelete,
  hideOn,
  className,
}: MessageActionsProps) {
  if (hideOn?.includes(role)) return null;
  return (
    <div
      className={cn(
        'mt-1 flex items-center gap-0.5 opacity-0 transition-opacity group-hover/msg:opacity-100 focus-within:opacity-100',
        className,
      )}
    >
      {onCopy ? <ActionButton onClick={onCopy} label="Copy" icon={Copy} /> : null}
      {onRegenerate && role === 'assistant' ? (
        <ActionButton onClick={onRegenerate} label="Regenerate" icon={RefreshCw} />
      ) : null}
      {onEdit && role === 'user' ? (
        <ActionButton onClick={onEdit} label="Edit" icon={Pencil} />
      ) : null}
      {onDelete ? <ActionButton onClick={onDelete} label="Delete" icon={Trash} destructive /> : null}
    </div>
  );
}

const ActionButton = memo(function ActionButton({
  onClick,
  label,
  icon: Icon,
  destructive,
}: {
  onClick: () => void;
  label: string;
  icon: typeof Copy;
  destructive?: boolean;
}) {
  const styles = useChatDestructiveStyles();
  return (
    <button
      type="button"
      onClick={onClick}
      aria-label={label}
      className={cn(
        'rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground',
        destructive && cn(styles.hover, 'hover:text-destructive'),
      )}
    >
      <Icon aria-hidden className="size-3" />
    </button>
  );
});

export const MessageActions = memo(MessageActionsRaw);
