"use client";

import { useState } from "react";
import { Wrench, ChevronDown, ChevronRight, Lightbulb } from "lucide-react";
import type { Message, ToolCall } from "@/lib/types";

type Verbosity = "compact" | "normal" | "full";

interface Props {
  message: Message;
  toolResults: Map<string, { name: string; content: string }>;
  verbosity?: Verbosity;
  showTimestamp?: boolean;
}

function ReasoningBlock({ text }: { text: string }) {
  const [open, setOpen] = useState(false);
  const preview = text.slice(0, 120);

  return (
    <div className="mb-2">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1 text-[11px] py-0.5 px-1.5 rounded-md active:bg-white/[0.04]"
        style={{ color: "#e0a030" }}
      >
        <Lightbulb size={10} />
        <span>Thinking</span>
        {open ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
      </button>
      {open ? (
        <pre className="mt-1 text-[12px] whitespace-pre-wrap leading-relaxed max-h-[50vh] overflow-y-auto px-2" style={{ color: "var(--text-2)" }}>
          {text}
        </pre>
      ) : (
        <p className="mt-0.5 text-[11px] px-2 line-clamp-1" style={{ color: "var(--text-3)" }}>
          {preview}{text.length > 120 ? "..." : ""}
        </p>
      )}
    </div>
  );
}

function ToolCallBlock({ tc, result, defaultOpen, showResult }: { tc: ToolCall; result?: { name: string; content: string }; defaultOpen: boolean; showResult: boolean }) {
  const [open, setOpen] = useState(defaultOpen);
  let args: Record<string, unknown> = {};
  try { args = JSON.parse(tc.function.arguments); } catch {}

  return (
    <div className="mt-1.5">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1 text-[11px] py-0.5 px-1.5 rounded-md active:bg-white/[0.04]"
        style={{ color: "var(--accent)" }}
      >
        <Wrench size={10} />
        <span className="font-mono">{tc.function.name}</span>
        {open ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
      </button>
      {open && (
        <div className="mt-1 ml-2 pl-2 space-y-1" style={{ borderLeft: "2px solid var(--border)" }}>
          <pre className="text-[11px] overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto" style={{ color: "var(--text-3)" }}>
            {JSON.stringify(args, null, 2)}
          </pre>
          {showResult && result && (
            <pre className="text-[11px] overflow-x-auto whitespace-pre-wrap max-h-48 overflow-y-auto" style={{ color: "var(--text-3)", opacity: 0.6 }}>
              {result.content.slice(0, 2000)}{result.content.length > 2000 ? "..." : ""}
            </pre>
          )}
        </div>
      )}
    </div>
  );
}

export function MessageBubble({ message, toolResults, verbosity = "normal", showTimestamp = false }: Props) {
  const isUser = message.role === "user";
  const content = message.content || "";
  const reasoning = message.reasoning || "";

  let toolCalls: ToolCall[] = [];
  if (message.tool_calls) {
    try { toolCalls = JSON.parse(message.tool_calls); } catch {}
  }

  if (!content && toolCalls.length === 0 && !reasoning) return null;

  const showTools = verbosity !== "compact" && toolCalls.length > 0;
  const showReasoning = verbosity === "full" && reasoning;
  const expandTools = verbosity === "full";

  return (
    <div className={`flex ${isUser ? "justify-end" : "justify-start"}`}>
      <div
        className="max-w-[88%] rounded-2xl px-3.5 py-2.5"
        style={{
          background: isUser ? "var(--accent)" : "var(--bg-raised)",
          color: isUser ? "white" : "var(--text-1)",
        }}
      >
        {/* Reasoning / thinking */}
        {showReasoning && <ReasoningBlock text={reasoning} />}

        {/* Content */}
        {content && (
          <p className="text-[14px] whitespace-pre-wrap leading-relaxed break-words">
            {verbosity === "compact" && content.length > 300
              ? content.slice(0, 300) + "..."
              : content}
          </p>
        )}

        {/* Tool calls */}
        {showTools && (
          <div>
            {expandTools ? (
              toolCalls.map((tc) => (
                <ToolCallBlock key={tc.id} tc={tc} result={toolResults.get(tc.id)} defaultOpen={true} showResult={true} />
              ))
            ) : toolCalls.length <= 3 ? (
              toolCalls.map((tc) => (
                <ToolCallBlock key={tc.id} tc={tc} result={toolResults.get(tc.id)} defaultOpen={false} showResult={false} />
              ))
            ) : (
              <CollapsedTools toolCalls={toolCalls} toolResults={toolResults} />
            )}
          </div>
        )}

        {/* No content indicator for tool-only messages in full mode */}
        {!content && showTools && verbosity === "full" && (
          <div className="text-[11px] mt-1" style={{ color: "var(--text-3)" }}>
            (tool calls only)
          </div>
        )}

        {/* Timestamp */}
        {showTimestamp && message.timestamp && (
          <div className="text-[10px] mt-1" style={{ color: isUser ? "rgba(255,255,255,0.5)" : "var(--text-3)" }}>
            {new Date(message.timestamp * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
          </div>
        )}
      </div>
    </div>
  );
}

function CollapsedTools({ toolCalls, toolResults }: { toolCalls: ToolCall[]; toolResults: Map<string, { name: string; content: string }> }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="mt-1.5">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1 text-[11px] py-0.5 px-1.5 rounded-md active:bg-white/[0.04]"
        style={{ color: "var(--accent)" }}
      >
        <Wrench size={10} />
        <span>{toolCalls.length} tool calls</span>
        {open ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
      </button>
      {open && toolCalls.map((tc) => (
        <ToolCallBlock key={tc.id} tc={tc} result={toolResults.get(tc.id)} defaultOpen={false} showResult={false} />
      ))}
    </div>
  );
}
