import type {
  PuzzleAgentActionRequest,
  PuzzleAgentOperationRecord,
} from '../../../packages/shared/src/contracts/puzzleAgentActions';
import type {
  PuzzleAgentSessionSnapshot,
  SendPuzzleAgentMessageRequest,
} from '../../../packages/shared/src/contracts/puzzleAgentSession';
import {
  buildCreationAgentChatMessage,
  createCreationAgentChatQuickActions,
  createCreationAgentClientMessageId,
  resolveCreationAgentQuickActionMessage,
} from '../../services/creation-agent';
import {
  type CreationAgentOperationView,
  type CreationAgentSessionView,
  type CreationAgentTheme,
  CreationAgentWorkspace,
} from '../creation-agent';

type PuzzleAgentWorkspaceProps = {
  session: PuzzleAgentSessionSnapshot | null;
  activeOperation?: PuzzleAgentOperationRecord | null;
  streamingReplyText?: string;
  isStreamingReply?: boolean;
  isBusy?: boolean;
  error?: string | null;
  onBack: () => void;
  onSubmitMessage: (payload: SendPuzzleAgentMessageRequest) => void;
  onExecuteAction: (payload: PuzzleAgentActionRequest) => void;
};

const PUZZLE_AGENT_THEME: CreationAgentTheme = {
  accentTextClass: 'text-amber-100/84',
  accentBgClass: 'bg-amber-200',
  accentButtonClass: 'bg-amber-200 shadow-amber-950/20',
  userBubbleClass: 'bg-amber-600 text-white',
  heroClass:
    'border border-amber-100/16 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.18),transparent_32%),linear-gradient(135deg,rgba(76,29,19,0.96),rgba(20,24,35,0.96))]',
  anchorGridClass: 'grid gap-2 sm:grid-cols-2 xl:grid-cols-5',
};

function mapPuzzleSession(
  session: PuzzleAgentSessionSnapshot,
): CreationAgentSessionView {
  return {
    sessionId: session.sessionId,
    // 所有玩法的 Agent 聊天页顶部模块只保留操作与进度，不展示标题和引导副文案。
    title: null,
    assistantSummary: null,
    currentTurn: session.currentTurn,
    progressPercent: session.progressPercent,
    anchors: [
      session.anchorPack.themePromise,
      session.anchorPack.visualSubject,
      session.anchorPack.visualMood,
      session.anchorPack.compositionHooks,
      session.anchorPack.tagsAndForbidden,
    ],
    messages: session.messages,
    recommendedReplies: [],
  };
}

function mapPuzzleOperation(
  operation: PuzzleAgentOperationRecord | null | undefined,
): CreationAgentOperationView | null {
  if (!operation) {
    return null;
  }

  return {
    operationId: operation.operationId,
    type: operation.type,
    status: operation.status,
    phaseLabel: operation.phaseLabel,
    phaseDetail: operation.phaseDetail,
    progress: operation.progress,
    error: operation.error,
  };
}

/**
 * 拼图 Agent 共创工作区只保留品类适配，聊天 UI 与进度管理统一走 CreationAgentWorkspace。
 */
export function PuzzleAgentWorkspace({
  session,
  activeOperation = null,
  streamingReplyText = '',
  isStreamingReply = false,
  isBusy = false,
  error = null,
  onBack,
  onSubmitMessage,
  onExecuteAction,
}: PuzzleAgentWorkspaceProps) {
  return (
    <CreationAgentWorkspace
      session={session ? mapPuzzleSession(session) : null}
      theme={PUZZLE_AGENT_THEME}
      loadingText="正在准备拼图共创工作区..."
      composerPlaceholder="说说题材、主体、气质或你不希望出现的元素..."
      primaryActionLabel="生成结果页"
      activeOperation={mapPuzzleOperation(activeOperation)}
      streamingReplyText={streamingReplyText}
      isStreamingReply={isStreamingReply}
      isBusy={isBusy}
      error={error}
      quickActions={createCreationAgentChatQuickActions()}
      onBack={onBack}
      onSubmitText={(text) => {
        onSubmitMessage(
          buildCreationAgentChatMessage({
            clientMessageId: createCreationAgentClientMessageId('puzzle'),
            text,
          }),
        );
      }}
      onPrimaryAction={() => {
        onExecuteAction({ action: 'compile_puzzle_draft' });
      }}
      onQuickAction={(action) => {
        const quickActionMessage = resolveCreationAgentQuickActionMessage(
          action.key,
          '请总结一下当前已经成形的拼图设定。',
        );
        onSubmitMessage(
          buildCreationAgentChatMessage({
            clientMessageId: createCreationAgentClientMessageId('puzzle'),
            ...quickActionMessage,
          }),
        );
      }}
    />
  );
}

export default PuzzleAgentWorkspace;
