import type { ReactElement } from "react";

import type { ChatMessage } from "../../types/domain";
import { formatBeijingTime, formatDuration, shortToken, toneClass } from "../../utils";

interface MessagePendingContextProps {
  message: ChatMessage;
  codeAgentTimeoutMs: number;
}

export function MessagePendingContext({ message, codeAgentTimeoutMs }: MessagePendingContextProps): ReactElement | null {
  if (message.status !== "running") return null;
  const fields: Array<[string, string | null | undefined, boolean]> = [
    ["状态", "处理中", false],
    ["traceId", typeof message.traceId === "string" ? message.traceId : null, true],
    ["conversation", typeof message.conversationId === "string" ? message.conversationId : null, true],
    ["session", message.sessionId ?? message.runnerTrace?.sessionId ?? "等待后端分配", true],
    ["thread", message.threadId ?? message.runnerTrace?.threadId ?? "等待后端分配", false],
    ["sessionStatus", typeof message.runnerTrace?.sessionStatus === "string" ? message.runnerTrace.sessionStatus : null, false],
    ["lifecycle", typeof message.runnerTrace?.sessionLifecycleStatus === "string" ? message.runnerTrace.sessionLifecycleStatus : null, false],
    ["activityTimeout", `${formatDuration(codeAgentTimeoutMs)} 无新事件`, false]
  ];
  return (
    <section className="message-pending-context tone-border-pending" data-message-pending-context>
      <div className="message-pending-head">
        <span className={`state-tag tone-${toneClass("pending")}`} data-pending-tag>处理中</span>
        <span className="message-pending-summary">{message.runnerTrace?.waitingFor ? `等待 ${message.runnerTrace.waitingFor}` : "等待后端事件"}</span>
      </div>
      <div className="message-pending-grid" role="list">
        {fields.map(([label, value, copyable]) => {
          if (value === undefined || value === null || value === "") return null;
          return (
            <div key={label} className="message-pending-row" role="listitem">
              <span className="message-pending-key">{label}</span>
              <span className="message-pending-value mono">{copyable ? shortToken(value, 32) : value}</span>
              <span className="message-pending-time">{formatBeijingTime(message.updatedAt ?? message.createdAt, { withSeconds: true })}</span>
            </div>
          );
        })}
      </div>
    </section>
  );
}
