import { FolderSearchIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import z from "zod";
import { TABS_TASK_NAMESPACE } from "@/i18n/resources";
import type { FileSystemFindFiles } from "@/api/generated/schemas";
import { FindFilesToolSchema } from "@/api/tool-schema";
import { getToolMessageMetadata } from "@/types/message";
import { CodeBlock } from "@/components/ai-elements/code-block";
import { tryParseSchema } from "@/lib/utils";
import type { ToolMessageProps } from ".";
import {
  BuiltInToolContainer,
  BuiltInToolContent,
  BuiltInToolError,
  BuiltInToolHeader,
  BuiltInToolTitle,
} from "./components/BuiltInTool";
import { ToolConfirmation } from "./components/ToolConfirmation";
import { useAgentTaskAction } from "../../../hooks/use-agent-task";
import { useToolArgument } from "../../../hooks/use-tool-argument";
import { useToolActionable } from "../../../hooks/use-tool-actionable";

const findFilesResultSchema = z.object({
  matches: z.array(z.string()),
  total: z.number(),
  search_root: z.string(),
});

function FindFilesContent({ result }: { result: string }) {
  const { t } = useTranslation(TABS_TASK_NAMESPACE);
  const parsedResult = tryParseSchema(findFilesResultSchema, result);
  if (parsedResult === null) {
    return (
      <p className="px-4 pb-4 text-muted-foreground text-sm">
        {t("tool.find_files.parse_error")}
      </p>
    );
  }
  return (
    <div className="px-4 pb-4">
      <CodeBlock
        code={parsedResult.matches.join("\n")}
        language="text"
        showLineNumbers={false}
      />
    </div>
  );
}

export function FindFiles({ message }: ToolMessageProps) {
  const { t } = useTranslation(TABS_TASK_NAMESPACE);
  const { reviewTool } = useAgentTaskAction();
  const toolArguments = useToolArgument<FileSystemFindFiles>(
    message,
    FindFilesToolSchema,
  );
  const { disabled, markAsSubmitted } = useToolActionable(message);
  const { userApproval, risk } = getToolMessageMetadata(message);

  const content = (() => {
    if (message.isStreaming) {
      return (
        <p className="px-4 pb-4 text-muted-foreground text-sm">
          {t("tool.find_files.generating")}
        </p>
      );
    }
    if (message.error) {
      return <BuiltInToolError error={message.error} />;
    }
    if (message.result !== null) {
      return <FindFilesContent result={message.result as string} />;
    }
    if (toolArguments === null) {
      return (
        <p className="px-4 pb-4 text-muted-foreground text-sm">
          {t("tool.find_files.parse_error")}
        </p>
      );
    }
  })();

  return (
    <BuiltInToolContainer id={message.call_id}>
      <BuiltInToolHeader icon={FolderSearchIcon} risk={risk}>
        <BuiltInToolTitle title={t("tool.find_files.title")}>
          {toolArguments && (
            <div className="truncate font-medium font-mono text-sm">
              {toolArguments.pattern}
            </div>
          )}
        </BuiltInToolTitle>
      </BuiltInToolHeader>
      <BuiltInToolContent>{content}</BuiltInToolContent>
      {userApproval && (
        <ToolConfirmation
          state={userApproval}
          disabled={disabled}
          riskLevel={risk.level}
          onSubmit={markAsSubmitted}
          onAccept={() => reviewTool(message.call_id, "approved")}
          onReject={() => reviewTool(message.call_id, "denied")}
        />
      )}
    </BuiltInToolContainer>
  );
}
