import { formatDuration } from "@utils/format.ts";
import { Timer, Wrench } from "lucide-react";
import { useState } from "react";

import type { ChatMessageAssistantTool } from "../textGeneration/types.ts";
import { Loader } from "../theme";
import cn from "../utils/classnames.ts";

export default function MessageToolCall({
  tool,
  className = "",
}: {
  tool: ChatMessageAssistantTool;
  className?: string;
}) {
  const [expanded, setExpanded] = useState<boolean>(false);

  const isLoading = tool.result === "";

  return (
    <div
      className={cn(
        className,
        "rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800"
      )}
    >
      <div className="flex items-center justify-between gap-3">
        <button
          className="flex w-full cursor-pointer items-center justify-between gap-2 text-xs text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100"
          onClick={() => setExpanded(!expanded)}
        >
          <span className="flex items-center gap-2">
            {isLoading ? <Loader size="xs" /> : <Wrench className="h-3 w-3" />}
            {isLoading ? "calling tool" : "called tool"} <b>{tool.name}</b>
          </span>
          <span className="flex items-center gap-1 opacity-60">
            <Timer className="h-3 w-3" />
            {formatDuration(tool.time)}
          </span>
        </button>
      </div>
      {expanded && (
        <div className="mt-2 space-y-2">
          <div>
            <div className="mb-1 text-xs text-gray-600 dark:text-gray-400">
              Function:
            </div>
            <code className="block overflow-hidden rounded bg-white p-2 font-mono text-xs text-blue-600 dark:bg-gray-900 dark:text-blue-400">
              {tool.functionSignature}
            </code>
          </div>
          <div>
            <div className="mb-1 text-xs text-gray-600 dark:text-gray-400">
              Result:
            </div>
            <div className="overflow-hidden rounded bg-white p-2 text-sm whitespace-pre-wrap text-gray-900 dark:bg-gray-900 dark:text-gray-100">
              {tool.result || "loading.."}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
