"use client";

import { useState, useCallback, useRef, useEffect, memo } from "react";
import type { ToolCallBlock } from "@optage/sdk/client";
import { isAgentTool } from "@optage/sdk/client";

interface ToolCallCardProps {
  block: ToolCallBlock;
}

export function ToolCallCard({ block }: ToolCallCardProps) {
  if (isAgentTool(block.toolName)) {
    return <AgentToolCard block={block} />;
  }
  return <SimpleToolCard block={block} />;
}

/* ── Simple tool card (Read, Glob, Grep, Bash, etc.) ──────────── */

function SimpleToolCard({ block }: { block: ToolCallBlock }) {
  const [expanded, setExpanded] = useState(false);
  const toggle = useCallback(() => setExpanded((v) => !v), []);

  const statusColor = getStatusColor(block.toolStatus);
  const statusIcon = getStatusIcon(block.toolStatus);

  return (
    <div className="my-1">
      <button
        onClick={toggle}
        className="flex items-center gap-2 hover:bg-rp-surface/50 rounded-lg px-2 py-1.5 text-left group"
      >
        <span className={`shrink-0 ${statusColor}`}>{statusIcon}</span>
        <span className="text-r-sm text-rp-muted truncate">
          {block.toolName}
        </span>
        <ToolStatusLabel status={block.toolStatus} />
      </button>

      {expanded && block.toolResultRaw && (
        <pre className="bg-rp-surface rounded-lg p-3 ml-4 mt-1 text-r-xs text-rp-text font-mono whitespace-pre-wrap break-words max-h-64 overflow-y-auto">
          {block.toolResult
            ? `${block.toolResult.stdout}${block.toolResult.stderr ? `\n[stderr] ${block.toolResult.stderr}` : ""}`
            : block.toolResultRaw}
        </pre>
      )}
    </div>
  );
}

/* ── Agent/Task tool card — fixed log window ──────────────────── */

function AgentToolCard({ block }: { block: ToolCallBlock }) {
  const [expanded, setExpanded] = useState(true);
  const toggle = useCallback(() => setExpanded((v) => !v), []);
  const logRef = useRef<HTMLDivElement>(null);

  const isActive =
    block.toolStatus === "streaming" || block.toolStatus === "executing";
  const subs = block.subAgentToolCalls || [];

  // Auto-scroll log to bottom when new sub-tool calls arrive
  useEffect(() => {
    if (logRef.current && isActive) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [subs.length, subs[subs.length - 1]?.toolStatus, isActive]);

  // Parse agent description from args
  const agentDesc = (() => {
    try {
      const parsed = block.toolArgsParsed || JSON.parse(block.toolArgs);
      return (parsed as Record<string, string>)?.description || "";
    } catch {
      return "";
    }
  })();

  const statusColor = getStatusColor(block.toolStatus);
  const statusIcon = getStatusIcon(block.toolStatus);

  return (
    <div
      className={`my-2 rounded-xl border overflow-hidden transition-colors ${
        isActive ? "border-rp-accent/40" : "border-rp-border/40"
      }`}
    >
      {/* Header bar */}
      <button
        onClick={toggle}
        className="w-full flex items-center gap-2 px-3 py-2.5 bg-rp-surface hover:bg-rp-surface/80 transition-colors text-left"
      >
        <span className={`shrink-0 ${statusColor}`}>{statusIcon}</span>
        <AgentIcon />
        <span className="text-r-sm text-rp-text font-semibold truncate">
          {block.toolName}
        </span>
        {agentDesc && (
          <span className="text-r-2xs text-rp-muted truncate hidden sm:inline">
            — {agentDesc}
          </span>
        )}
        <div className="ml-auto flex items-center gap-2 shrink-0">
          {block.elapsedSeconds != null && block.elapsedSeconds > 0 && (
            <span className="text-r-2xs text-rp-muted tabular-nums">
              {formatElapsed(block.elapsedSeconds)}
            </span>
          )}
          <ToolStatusLabel status={block.toolStatus} />
          <ChevronIcon expanded={expanded} />
        </div>
      </button>

      {/* Log window */}
      {expanded && (
        <div
          ref={logRef}
          className="bg-rp-surface-alt overflow-y-auto font-mono text-r-xs leading-5 scroll-smooth"
          style={{ maxHeight: 320, minHeight: subs.length > 0 ? 80 : 40 }}
        >
          {subs.length === 0 && isActive && (
            <div className="px-3 py-2 text-rp-muted">
              Waiting for subagent...
            </div>
          )}
          {subs.map((sub, i) => (
            <SubAgentLogEntry key={sub.id} sub={sub} />
          ))}

          {/* Final result summary */}
          {block.toolStatus === "done" && block.toolResultRaw && (
            <AgentResultSummary raw={block.toolResultRaw} />
          )}
          {block.toolStatus === "error" && block.toolResultRaw && (
            <div className="px-3 py-2 border-t border-rp-error/20 bg-rp-error/[0.06]">
              <span className="text-rp-error text-r-xs">
                {block.toolResultRaw.slice(0, 500)}
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ── Sub-agent log entry (single row in the log window) ───────── */

const SubAgentLogEntry = memo(function SubAgentLogEntry({
  sub,
}: {
  sub: ToolCallBlock;
}) {
  const [showResult, setShowResult] = useState(false);
  const toggle = useCallback(() => setShowResult((v) => !v), []);

  const isActive =
    sub.toolStatus === "streaming" || sub.toolStatus === "executing";
  const isDone = sub.toolStatus === "done";
  const isError = sub.toolStatus === "error";

  // Compact arg summary
  const argSummary = (() => {
    try {
      const parsed = sub.toolArgsParsed || JSON.parse(sub.toolArgs);
      if (!parsed) return "";
      // Show the most useful arg for common tools
      if (parsed.pattern) return String(parsed.pattern);
      if (parsed.file_path) return String(parsed.file_path);
      if (parsed.command) return String(parsed.command).slice(0, 80);
      if (parsed.query) return String(parsed.query).slice(0, 80);
      // Fallback: first string value
      const vals = Object.values(parsed);
      const first = vals.find((v) => typeof v === "string");
      return first ? String(first).slice(0, 80) : "";
    } catch {
      return sub.toolArgs.slice(0, 80);
    }
  })();

  // Compact result preview
  const resultPreview = (() => {
    if (!sub.toolResultRaw) return "";
    const raw = sub.toolResult?.stdout || sub.toolResultRaw;
    const lines = raw.split("\n").filter(Boolean);
    if (lines.length <= 1) return lines[0]?.slice(0, 120) || "";
    return `${lines[0]?.slice(0, 100)}  (+${lines.length - 1} lines)`;
  })();

  return (
    <div
      className={`group border-b border-rp-border/10 last:border-0 ${
        isActive ? "bg-rp-accent/[0.04]" : ""
      }`}
    >
      {/* Main row */}
      <button
        onClick={toggle}
        disabled={!sub.toolResultRaw}
        className="w-full flex items-start gap-2 px-3 py-1.5 text-left hover:bg-rp-surface/30 transition-colors disabled:cursor-default"
      >
        {/* Status icon */}
        <span className={`shrink-0 mt-px ${getLogStatusColor(sub.toolStatus)}`}>
          {isActive ? (
            <SpinnerIcon />
          ) : isDone ? (
            "\u2713"
          ) : isError ? (
            "\u2717"
          ) : (
            "\u25CB"
          )}
        </span>

        {/* Tool name */}
        <span
          className={`shrink-0 font-semibold ${
            isActive ? "text-rp-accent" : "text-rp-info"
          }`}
        >
          {sub.toolName}
        </span>

        {/* Arg summary */}
        {argSummary && (
          <span className="text-rp-muted truncate">{argSummary}</span>
        )}

        {/* Right side: elapsed / status */}
        <span className="ml-auto flex items-center gap-2 shrink-0">
          {isActive && (
            <span className="text-rp-accent text-r-2xs">running</span>
          )}
          {isDone && resultPreview && !showResult && (
            <span className="text-rp-muted/40 text-r-2xs opacity-0 group-hover:opacity-100 transition-opacity">
              click to expand
            </span>
          )}
        </span>
      </button>

      {/* Expanded result */}
      {showResult && sub.toolResultRaw && (
        <div className="mx-3 mb-2 ml-10 rounded-lg bg-rp-surface overflow-hidden">
          <div className="px-3 py-1 border-b border-rp-border/10 flex items-center justify-between">
            <span className="text-r-2xs text-rp-muted/50 font-medium">
              Result
            </span>
            {sub.toolResult?.stderr && (
              <span className="text-r-2xs text-rp-error">has errors</span>
            )}
          </div>
          <pre className="px-3 py-2 text-r-xs text-rp-text whitespace-pre-wrap break-words max-h-48 overflow-y-auto">
            {sub.toolResult
              ? `${sub.toolResult.stdout}${sub.toolResult.stderr ? `\n[stderr] ${sub.toolResult.stderr}` : ""}`
              : sub.toolResultRaw}
          </pre>
        </div>
      )}
    </div>
  );
});

/* ── Agent result summary (bottom of log window) ──────────────── */

function AgentResultSummary({ raw }: { raw: string }) {
  // Clean text = remove metadata
  let cleanText = raw
    .replace(/<usage>[\s\S]*?<\/usage>/g, "")
    .replace(/agentId:\s*\S+[^\n]*/g, "")
    .trim();

  // Truncate long results
  if (cleanText.length > 300) {
    cleanText = cleanText.slice(0, 300) + "...";
  }

  if (!cleanText) return null;

  return (
    <div className="px-3 py-2 text-rp-muted text-r-xs whitespace-pre-wrap">
      {cleanText}
    </div>
  );
}

/* ── Shared helpers ───────────────────────────────────────────── */

function ToolStatusLabel({ status }: { status: ToolCallBlock["toolStatus"] }) {
  if (status === "streaming" || status === "executing") {
    return (
      <span className="text-r-2xs text-rp-muted ml-auto">
        {status === "streaming" ? "streaming..." : "running..."}
      </span>
    );
  }
  return null;
}

function getStatusColor(status: ToolCallBlock["toolStatus"]): string {
  switch (status) {
    case "streaming":
    case "executing":
      return "text-rp-info";
    case "done":
      return "text-rp-success";
    case "error":
      return "text-rp-error";
    default:
      return "text-rp-muted";
  }
}

function getLogStatusColor(status: ToolCallBlock["toolStatus"]): string {
  switch (status) {
    case "streaming":
    case "executing":
      return "text-rp-accent";
    case "done":
      return "text-rp-success";
    case "error":
      return "text-rp-error";
    default:
      return "text-rp-muted/50";
  }
}

function getStatusIcon(status: ToolCallBlock["toolStatus"]): string {
  switch (status) {
    case "streaming":
    case "executing":
      return "\u25CB";
    case "done":
      return "\u2713";
    case "error":
      return "\u2717";
    default:
      return "\u25CB";
  }
}

function formatElapsed(seconds: number): string {
  if (seconds < 60) return `${Math.round(seconds)}s`;
  const m = Math.floor(seconds / 60);
  const s = Math.round(seconds % 60);
  return `${m}m${s > 0 ? ` ${s}s` : ""}`;
}

/* ── SVG icons ────────────────────────────────────────────────── */

function AgentIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 16 16"
      fill="none"
      className="shrink-0 text-rp-accent/70"
    >
      <rect
        x="2"
        y="2"
        width="12"
        height="12"
        rx="3"
        stroke="currentColor"
        strokeWidth="1.5"
      />
      <circle cx="6" cy="7" r="1.2" fill="currentColor" />
      <circle cx="10" cy="7" r="1.2" fill="currentColor" />
      <path
        d="M5.5 10.5C6 11.3 7 11.8 8 11.8C9 11.8 10 11.3 10.5 10.5"
        stroke="currentColor"
        strokeWidth="1.2"
        strokeLinecap="round"
      />
    </svg>
  );
}

function SpinnerIcon() {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 12 12"
      className="animate-spin"
    >
      <circle
        cx="6"
        cy="6"
        r="4.5"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeDasharray="14 14"
        strokeLinecap="round"
      />
    </svg>
  );
}

function ChevronIcon({ expanded }: { expanded: boolean }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 14 14"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      className={`transition-transform shrink-0 text-rp-muted ${
        expanded ? "rotate-180" : ""
      }`}
    >
      <path d="M4 5.5L7 8.5L10 5.5" />
    </svg>
  );
}
