import type { ReactElement } from "react";

import type { ChatMessage } from "../../types/domain";
import { toneClass } from "../../utils";

interface MessageActionsProps {
  message: ChatMessage;
  onCancel(): void;
  onRetry(): void;
}

export function MessageActions({ message, onCancel, onRetry }: MessageActionsProps): ReactElement | null {
  if (message.role !== "agent") return null;
  const status = String(message.status ?? "");
  const buttons: ReactElement[] = [];
  if (status === "running") {
    buttons.push(actionButton("取消当前请求", "cancel", onCancel, "取消当前 in-flight Codex stdio 请求"));
    if (message.retryInput) {
      buttons.push(actionButton("重试上一条", "retry", onRetry, "保留 sessionId/trace 并重新发送上一条输入"));
    }
  }
  if (canRetryTerminal(message) && message.retryInput) {
    buttons.push(actionButton("重试上一条", "retry", onRetry, "保留 conversation/trace 记录并重新发送上一条输入"));
  }
  if (buttons.length === 0 && !message.traceReplayStatus) return null;
  return (
    <div className={`message-actions tone-border-${toneClass(message.status)}`} role="toolbar" aria-label="消息操作">
      {buttons}
      {message.traceReplayStatus ? <span className="message-action-status">{message.traceReplayStatus}</span> : null}
    </div>
  );
}

function actionButton(label: string, action: string, onClick: () => void, title: string): ReactElement {
  return <button type="button" className={`message-action message-action-${action}`} title={title} onClick={onClick}>{label}</button>;
}

function canRetryTerminal(message: ChatMessage): boolean {
  return ["failed", "timeout", "error", "canceled", "blocked"].includes(String(message.status ?? "").toLowerCase());
}
