import {
  Tool,
  ToolContent,
  ToolInput,
  ToolOutput,
} from "@code/ui/components/ai-elements/tool";
import { MobileChatToolCall } from "@code/ui/components/mobile-chat";
import { Search, SquareTerminal } from "lucide-react";

import type { ChatToolCallProps } from "@/lib/chat/types";

export const ChatToolCall = ({ part }: ChatToolCallProps) => {
  let detail =
    typeof part.input === "string"
      ? part.input
      : JSON.stringify(part.input, null, 2);
  let status = "running";
  let tone: "error" | "neutral" | "success" = "neutral";

  if (part.state === "output-available") {
    detail =
      typeof part.output === "string"
        ? part.output
        : JSON.stringify(part.output, null, 2);
    status = "done";
    tone = "success";
  } else if (part.state === "output-error") {
    detail = part.errorText;
    status = "failed";
    tone = "error";
  }

  const isSearch = part.toolName.toLowerCase().includes("search");
  const output = part.state === "output-available" ? part.output : undefined;
  const errorText = part.state === "output-error" ? part.errorText : undefined;

  return (
    <Tool className="mb-0 w-full border-0" defaultOpen>
      <ToolContent className="space-y-0 p-0">
        <MobileChatToolCall
          detail={detail}
          icon={
            isSearch ? (
              <Search className="size-3" strokeWidth={2.2} />
            ) : (
              <SquareTerminal className="size-3" strokeWidth={2.2} />
            )
          }
          status={status}
          tone={tone}
          toolName={part.toolName}
        />
        <div className="sr-only">
          <ToolInput input={part.input} />
          <ToolOutput errorText={errorText} output={output} />
        </div>
      </ToolContent>
    </Tool>
  );
};
