"use client";

import { useState } from "react";
import { ChevronRight, Loader2, Wrench, CheckCircle2, Brain, AlertCircle, XCircle } from "lucide-react";
import { cn } from "@/lib/utils";

export type ThinkingStep = {
  type: "thinking" | "tool_call" | "tool_result" | "error";
  content?: string;
  name?: string;
  result?: string;
  success?: boolean;
};

interface ThinkingBlockProps {
  steps: ThinkingStep[];
  isStreaming: boolean;
}

function formatToolName(name: string): string {
  if (name.includes("__")) {
    const [server, tool] = name.split("__");
    return `${server} / ${tool}`;
  }
  return name;
}

function streamingSummary(steps: ThinkingStep[]): string {
  const last = steps[steps.length - 1];
  if (!last) return "처리 중...";
  switch (last.type) {
    case "thinking":
      return last.content ?? "처리 중...";
    case "tool_call":
      return `${formatToolName(last.name ?? "unknown")} 호출 중...`;
    case "tool_result":
      return last.success === false
        ? `${formatToolName(last.name ?? "unknown")} 오류 발생`
        : `${formatToolName(last.name ?? "unknown")} 완료`;
    case "error":
      return last.content ?? "오류 발생";
    default:
      return "처리 중...";
  }
}

export function ThinkingBlock({ steps, isStreaming }: ThinkingBlockProps) {
  const [expanded, setExpanded] = useState(isStreaming);

  if (steps.length === 0) return null;

  const toolCalls = steps.filter((s) => s.type === "tool_call");
  const toolNames = toolCalls.map((s) => s.name ?? "unknown");
  const uniqueTools = [...new Set(toolNames)];
  const hasError = steps.some((s) => s.type === "error" || (s.type === "tool_result" && s.success === false));

  // Auto-expand while streaming, allow manual toggle when done
  const isOpen = isStreaming || expanded;

  const summary =
    uniqueTools.length > 0
      ? `${uniqueTools.map(formatToolName).join(", ")} 도구를 사용했습니다`
      : "처리 완료";

  return (
    <div className="mb-3 rounded-2xl border border-foreground/5 bg-foreground/[0.02] backdrop-blur-sm overflow-hidden transition-all duration-300">
      {/* Header / Summary bar */}
      <button
        type="button"
        onClick={() => !isStreaming && setExpanded((prev) => !prev)}
        className={cn(
          "w-full flex items-center gap-2.5 px-4 py-2.5 text-left transition-colors duration-200",
          !isStreaming && "hover:bg-foreground/[0.03] cursor-pointer",
          isStreaming && "cursor-default"
        )}
      >
        {/* Left color bar indicator */}
        <div
          className={cn(
            "w-0.5 h-5 rounded-full shrink-0 transition-colors duration-500",
            isStreaming ? "bg-primary animate-pulse" : hasError ? "bg-red-400" : "bg-emerald-400"
          )}
        />

        {isStreaming ? (
          <Loader2 className="w-3.5 h-3.5 text-primary animate-spin shrink-0" />
        ) : hasError ? (
          <AlertCircle className="w-3.5 h-3.5 text-red-400 shrink-0" />
        ) : (
          <Brain className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
        )}

        <span className="text-[10px] font-bold text-muted-foreground/70 uppercase tracking-wider flex-1 truncate">
          {isStreaming ? streamingSummary(steps) : summary}
        </span>

        {!isStreaming && (
          <ChevronRight
            className={cn(
              "w-3.5 h-3.5 text-muted-foreground/40 transition-transform duration-200 shrink-0",
              expanded && "rotate-90"
            )}
          />
        )}
      </button>

      {/* Expanded detail */}
      {isOpen && (
        <div className="px-4 pb-3 space-y-1.5 animate-in fade-in slide-in-from-top-1 duration-300">
          <div className="h-px bg-foreground/5 mb-2" />
          {steps.map((step, idx) => (
            <StepRow key={idx} step={step} isLast={idx === steps.length - 1 && isStreaming} />
          ))}
        </div>
      )}
    </div>
  );
}

function StepRow({ step, isLast }: { step: ThinkingStep; isLast: boolean }) {
  switch (step.type) {
    case "thinking":
      return (
        <div className="flex items-center gap-2 py-1">
          {isLast ? (
            <Loader2 className="w-3 h-3 text-primary/60 animate-spin shrink-0" />
          ) : (
            <CheckCircle2 className="w-3 h-3 text-emerald-400/60 shrink-0" />
          )}
          <span className="text-[10px] font-medium text-muted-foreground/60">{step.content}</span>
        </div>
      );
    case "tool_call":
      return (
        <div className="flex items-center gap-2 py-1">
          <Wrench className="w-3 h-3 text-primary/70 shrink-0" />
          <span className="text-[10px] font-bold text-primary/70 uppercase tracking-wider">
            {formatToolName(step.name ?? "unknown")}
          </span>
          <span className="text-[10px] text-muted-foreground/40">호출</span>
        </div>
      );
    case "tool_result":
      return (
        <div className="flex items-start gap-2 py-1 pl-5">
          {step.success === false ? (
            <XCircle className="w-3 h-3 text-red-400/70 shrink-0 mt-0.5" />
          ) : (
            <CheckCircle2 className="w-3 h-3 text-emerald-400/60 shrink-0 mt-0.5" />
          )}
          <span className={cn(
            "text-[10px] leading-relaxed line-clamp-2 break-all",
            step.success === false ? "text-red-400/70" : "text-muted-foreground/50"
          )}>
            {step.result || "완료"}
          </span>
        </div>
      );
    case "error":
      return (
        <div className="flex items-center gap-2 py-1">
          <AlertCircle className="w-3 h-3 text-red-400/70 shrink-0" />
          <span className="text-[10px] font-medium text-red-400/70">{step.content}</span>
        </div>
      );
    default:
      return null;
  }
}
