import { useState } from 'react';

export interface ToolCallData {
  callId: string;
  movement: string;
  name: string;
  args: string;
  result: string;
  isError: boolean;
  durationMs: number;
  cacheHit: boolean;
}

export function parseToolCallComment(body: string): ToolCallData | null {
  try {
    const data = JSON.parse(body);
    if (data && data.type === 'tool_call' && typeof data.name === 'string') {
      return {
        callId: data.callId ?? '',
        movement: data.movement ?? '',
        name: data.name,
        args: typeof data.args === 'string' ? data.args : JSON.stringify(data.args ?? {}),
        result: typeof data.result === 'string' ? data.result : '',
        isError: !!data.isError,
        durationMs: typeof data.durationMs === 'number' ? data.durationMs : 0,
        cacheHit: !!data.cacheHit,
      };
    }
  } catch { /* not tool_call JSON */ }
  return null;
}

function formatDuration(ms: number): string {
  if (ms < 1000) return `${ms}ms`;
  const sec = ms / 1000;
  if (sec < 10) return `${sec.toFixed(1)}s`;
  return `${Math.round(sec)}s`;
}

const PREVIEW_LINES = 25;

function truncateLines(text: string, maxLines: number): { display: string; truncated: boolean } {
  const lines = text.split('\n');
  if (lines.length <= maxLines) return { display: text, truncated: false };
  return { display: lines.slice(0, maxLines).join('\n'), truncated: true };
}

function summarizeArgs(name: string, argsStr: string): string {
  try {
    const args = JSON.parse(argsStr);
    if (!args || typeof args !== 'object') return '';
    // Common patterns: file_path, path, command, query, url
    const keys = ['file_path', 'path', 'command', 'cmd', 'query', 'url', 'pattern'];
    for (const k of keys) {
      if (typeof args[k] === 'string') {
        const v = args[k] as string;
        return v.length > 80 ? v.slice(0, 80) + '…' : v;
      }
    }
    // Fallback: first string value
    for (const v of Object.values(args)) {
      if (typeof v === 'string') {
        return v.length > 80 ? v.slice(0, 80) + '…' : v;
      }
    }
    // Fallback: keys
    return Object.keys(args).slice(0, 3).join(', ');
  } catch { /* ignore */ }
  return argsStr.slice(0, 80);
}

interface DisplayName {
  server: string | null;
  name: string;
}

function formatToolName(raw: string): DisplayName {
  // mcp__<server>__<tool> → split server/tool for compact display
  if (raw.startsWith('mcp__')) {
    const rest = raw.slice(5);
    const idx = rest.indexOf('__');
    if (idx > 0) {
      return { server: rest.slice(0, idx), name: rest.slice(idx + 2) };
    }
  }
  return { server: null, name: raw };
}

function ToolCallRow({ tc }: { tc: ToolCallData }) {
  const [open, setOpen] = useState(false);
  const summary = summarizeArgs(tc.name, tc.args);
  const argsPreview = truncateLines(tc.args, PREVIEW_LINES);
  const resultPreview = truncateLines(tc.result, PREVIEW_LINES);
  const display = formatToolName(tc.name);

  return (
    <li className="text-[11px] min-w-0">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="w-full text-left flex items-center gap-1.5 py-0.5 hover:bg-surface/50 rounded -mx-1 px-1 transition-colors min-w-0"
      >
        <svg
          className={`w-3 h-3 flex-shrink-0 text-slate-400 transition-transform ${open ? 'rotate-90' : ''}`}
          viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
        >
          <path d="M6 4l4 4-4 4" />
        </svg>
        <span className={`flex-shrink-0 ${tc.isError ? 'text-red-500' : 'text-emerald-600'}`}>
          {tc.isError ? '✕' : '✓'}
        </span>
        {display.server && (
          <span className="font-mono text-[10px] text-purple-500 bg-purple-50 px-1 py-px rounded flex-shrink-0">
            {display.server}
          </span>
        )}
        <span className="font-mono font-medium text-slate-700 flex-shrink-0">{display.name}</span>
        {summary && <span className="font-mono text-slate-500 truncate min-w-0">{summary}</span>}
        <span className="text-slate-400 tabular-nums ml-auto flex-shrink-0">
          {tc.cacheHit ? 'cache' : formatDuration(tc.durationMs)}
        </span>
      </button>
      {open && (
        <div className="ml-5 mt-1 mb-2 space-y-1.5">
          <div>
            <div className="text-[10px] text-slate-500 mb-0.5">args</div>
            <pre className="text-[10px] font-mono bg-surface/70 border border-hairline rounded px-1.5 py-1 overflow-x-auto whitespace-pre-wrap break-all">
              {argsPreview.display}
              {argsPreview.truncated && <span className="text-slate-400">{'\n…(truncated)'}</span>}
            </pre>
          </div>
          <div>
            <div className="text-[10px] text-slate-500 mb-0.5">result {tc.isError && <span className="text-red-500">(error)</span>}</div>
            <pre className="text-[10px] font-mono bg-surface/70 border border-hairline rounded px-1.5 py-1 overflow-x-auto whitespace-pre-wrap break-all max-h-64">
              {resultPreview.display}
              {resultPreview.truncated && <span className="text-slate-400">{'\n…(truncated)'}</span>}
            </pre>
          </div>
        </div>
      )}
    </li>
  );
}

interface Props {
  toolCalls: ToolCallData[];
}

export function ToolCallsSection({ toolCalls }: Props) {
  const [open, setOpen] = useState(false);
  if (toolCalls.length === 0) return null;

  // Single tool call: render the row directly. The "▸ 1 tool call" wrapper
  // adds no value and hides the actual tool name from the user, who has to
  // expand twice (section + row) to see it.
  if (toolCalls.length === 1) {
    return (
      <ul className="space-y-0">
        <ToolCallRow tc={toolCalls[0]!} />
      </ul>
    );
  }

  const errCount = toolCalls.filter(t => t.isError).length;

  return (
    <div className="flex flex-col">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 text-left py-1 hover:bg-surface/50 rounded -mx-1 px-1 transition-colors"
      >
        <svg
          className={`w-3 h-3 text-slate-400 transition-transform ${open ? 'rotate-90' : ''}`}
          viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
        >
          <path d="M6 4l4 4-4 4" />
        </svg>
        <span className="text-[11px] font-medium text-slate-600">
          {toolCalls.length} tool calls
        </span>
        {errCount > 0 && (
          <span className="text-[10px] text-red-500 font-mono">({errCount} error)</span>
        )}
      </button>
      {open && (
        <ul className="mt-0.5 space-y-0">
          {toolCalls.map((tc) => (
            <ToolCallRow key={tc.callId || `${tc.name}-${tc.durationMs}-${Math.random()}`} tc={tc} />
          ))}
        </ul>
      )}
    </div>
  );
}
