import { useState, useCallback } from "react";
import { marked } from "marked";
import { formatToolCallSignature } from "../lib/toolCallFormat";

// Configure marked with breaks enabled (consistent with ChatTurn)
marked.use({ breaks: true });

interface ToolCallDisplayProps {
  callId: string;
  name: string;
  parameters?: string;
  response?: string;
  createdAt?: string;
  defaultExpanded?: boolean;
}

/**
 * Renders a single tool call with expand/collapse behavior.
 *
 * Collapsed: ▸ toolName(param: value, ...)
 * Expanded: shows response (raw/markdown toggle) + metadata
 */
export default function ToolCallDisplay({
  callId,
  name,
  parameters,
  response,
  createdAt,
  defaultExpanded = false,
}: ToolCallDisplayProps) {
  const [expanded, setExpanded] = useState(defaultExpanded);
  const [renderMarkdown, setRenderMarkdown] = useState(false);
  const toggle = useCallback(() => setExpanded((p) => !p), []);

  const signature = formatToolCallSignature(name, parameters);
  const hasResponse = !!response;

  return (
    <div className="tool-call">
      {/* Header row — always visible, clickable to toggle */}
      <button
        onClick={toggle}
        className="tool-call-header flex items-start gap-1.5 text-xs font-mono text-text-secondary hover:text-text-primary transition-colors w-full text-left"
      >
        <span className="text-brand shrink-0">{expanded ? "▾" : "▸"}</span>
        <span className="break-all">{signature}</span>
        {hasResponse && !expanded && (
          <span className="text-green-500 shrink-0 ml-1">✓</span>
        )}
        {expanded && createdAt && (
          <span className="text-text-muted shrink-0 ml-auto text-[10px]">
            {new Date(createdAt).toLocaleTimeString()}
          </span>
        )}
      </button>

      {/* Expanded detail panel */}
      {expanded && (
        <div className="tool-call-detail ml-4 mt-1 space-y-1">
          {/* Metadata row */}
          <div className="flex items-center gap-3 text-[10px] font-mono text-text-muted">
            <span>id: {callId}</span>
            {createdAt && (
              <span>{new Date(createdAt).toLocaleTimeString()}</span>
            )}
          </div>

          {/* Response block */}
          {hasResponse && (
            <div className="tool-call-response-container">
              {/* Response header with RAW/MD toggle */}
              <div className="flex items-center justify-between text-[10px] font-mono text-text-muted mb-0.5">
                <span>Response</span>
                <div className="flex items-center gap-1">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setRenderMarkdown(false);
                    }}
                    className={`px-1.5 py-0.5 rounded text-[10px] transition-colors ${
                      !renderMarkdown
                        ? "bg-bg-elevated text-text-primary border border-border-default"
                        : "text-text-muted hover:text-text-secondary"
                    }`}
                  >
                    RAW
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setRenderMarkdown(true);
                    }}
                    className={`px-1.5 py-0.5 rounded text-[10px] transition-colors ${
                      renderMarkdown
                        ? "bg-bg-elevated text-text-primary border border-border-default"
                        : "text-text-muted hover:text-text-secondary"
                    }`}
                  >
                    MD
                  </button>
                </div>
              </div>

              {/* Response content */}
              {renderMarkdown ? (
                <div
                  className="tool-call-response-md gadget-markdown text-xs"
                  dangerouslySetInnerHTML={{
                    __html: marked.parse(response!) as string,
                  }}
                />
              ) : (
                <div className="tool-call-response-raw text-xs">
                  {response}
                </div>
              )}
            </div>
          )}

          {/* No response indicator */}
          {!hasResponse && (
            <div className="text-[10px] font-mono text-text-muted italic">
              No response
            </div>
          )}
        </div>
      )}
    </div>
  );
}
