"use client";

import { useMemo, useState } from "react";
import {
  Check,
  ChevronDown,
  Clipboard,
  Terminal,
  TriangleAlert,
  Wrench,
} from "lucide-react";

import { type SessionToolUseBlock } from "@/lib/api/claude-code";
import { cn } from "@/lib/utils";

type ToolCallBlockProps = {
  tool: SessionToolUseBlock;
};

function summarizeToolInput(tool: SessionToolUseBlock): string {
  const input = tool.input;
  const path =
    typeof input.file_path === "string"
      ? input.file_path
      : typeof input.path === "string"
        ? input.path
        : null;
  const command = typeof input.command === "string" ? input.command : null;
  const pattern = typeof input.pattern === "string" ? input.pattern : null;

  if (command) return command;
  if (path) return path;
  if (pattern) return pattern;

  const keys = Object.keys(input);
  if (keys.length === 0) return "No input";
  return keys.slice(0, 4).join(", ");
}

async function copyToClipboard(value: string, onCopied: () => void) {
  if (!value || typeof navigator === "undefined" || !navigator.clipboard) return;
  await navigator.clipboard.writeText(value);
  onCopied();
}

export function ToolCallBlock({ tool }: ToolCallBlockProps) {
  const [open, setOpen] = useState(false);
  const [copied, setCopied] = useState<"input" | "result" | null>(null);
  const inputJson = useMemo(() => JSON.stringify(tool.input, null, 2), [tool.input]);
  const summary = summarizeToolInput(tool);

  const markCopied = (kind: "input" | "result") => {
    setCopied(kind);
    window.setTimeout(() => setCopied(null), 1400);
  };

  return (
    <div
      className={cn(
        "overflow-hidden rounded-xl border bg-[color:var(--surface)] shadow-sm",
        tool.is_error
          ? "border-rose-400/30"
          : "border-[color:var(--border)]",
      )}
    >
      <button
        type="button"
        className="flex w-full items-center gap-3 px-4 py-3 text-left transition hover:bg-[color:var(--surface-muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--accent)]"
        aria-expanded={open}
        onClick={() => setOpen((value) => !value)}
      >
        <span
          className={cn(
            "flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ring-1",
            tool.is_error
              ? "bg-rose-500/15 text-rose-300 ring-rose-400/20"
              : "bg-cyan-500/15 text-cyan-300 ring-cyan-400/20",
          )}
        >
          {tool.tool_name.toLowerCase() === "bash" ? (
            <Terminal className="h-4 w-4" />
          ) : tool.is_error ? (
            <TriangleAlert className="h-4 w-4" />
          ) : (
            <Wrench className="h-4 w-4" />
          )}
        </span>
        <span className="min-w-0 flex-1">
          <span className="block text-sm font-semibold text-[color:var(--text)]">
            {tool.tool_name}
          </span>
          <span className="mt-0.5 block truncate font-mono text-xs text-[color:var(--text-muted)]">
            {summary}
          </span>
        </span>
        <ChevronDown
          className={cn(
            "h-4 w-4 shrink-0 text-[color:var(--text-muted)] transition",
            open && "rotate-180",
          )}
        />
      </button>

      {open ? (
        <div className="space-y-4 border-t border-[color:var(--border)] px-4 py-4">
          <div>
            <div className="mb-2 flex items-center justify-between gap-3">
              <p className="text-xs font-bold uppercase tracking-[0.18em] text-[color:var(--text-muted)]">
                Input
                {tool.input_truncated ? " · truncated" : ""}
              </p>
              <button
                type="button"
                className="inline-flex h-8 items-center gap-2 rounded-lg border border-[color:var(--border)] px-2.5 text-xs font-semibold text-[color:var(--text-muted)] transition hover:border-[color:var(--accent)] hover:text-[color:var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--accent)]"
                onClick={() => copyToClipboard(inputJson, () => markCopied("input"))}
              >
                {copied === "input" ? (
                  <Check className="h-3.5 w-3.5" />
                ) : (
                  <Clipboard className="h-3.5 w-3.5" />
                )}
                {copied === "input" ? "Copied" : "Copy"}
              </button>
            </div>
            <pre className="max-h-[420px] overflow-auto whitespace-pre-wrap break-words rounded-lg border border-[color:var(--border)] bg-[color:var(--bg)] p-3 font-mono text-xs leading-relaxed text-[color:var(--text)]">
              {inputJson}
            </pre>
          </div>

          {tool.result ? (
            <div>
              <div className="mb-2 flex items-center justify-between gap-3">
                <p className="text-xs font-bold uppercase tracking-[0.18em] text-[color:var(--text-muted)]">
                  Result
                  {tool.result_truncated ? " · truncated" : ""}
                </p>
                <button
                  type="button"
                  className="inline-flex h-8 items-center gap-2 rounded-lg border border-[color:var(--border)] px-2.5 text-xs font-semibold text-[color:var(--text-muted)] transition hover:border-[color:var(--accent)] hover:text-[color:var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--accent)]"
                  onClick={() =>
                    copyToClipboard(tool.result ?? "", () => markCopied("result"))
                  }
                >
                  {copied === "result" ? (
                    <Check className="h-3.5 w-3.5" />
                  ) : (
                    <Clipboard className="h-3.5 w-3.5" />
                  )}
                  {copied === "result" ? "Copied" : "Copy"}
                </button>
              </div>
              <pre
                className={cn(
                  "max-h-[420px] overflow-auto whitespace-pre-wrap break-words rounded-lg border p-3 font-mono text-xs leading-relaxed",
                  tool.is_error
                    ? "border-rose-400/30 bg-rose-950/20 text-rose-100"
                    : "border-[color:var(--border)] bg-[color:var(--bg)] text-[color:var(--text)]",
                )}
              >
                {tool.result}
              </pre>
            </div>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
