"use client";

import { useEffect, useState } from "react";

import { api } from "@/lib/api/client";
import { useToast } from "@/components/Toast";
import type { ToolDescriptorView } from "@/lib/api/types";

// 客户端拉取创作工具箱全量描述符（GET /skills/toolbox），供编辑器内联工具箱调用。
// 描述符只读、少变，进面板时拉一次即可。
export type ToolboxStatus = "loading" | "ready" | "error";

export interface UseToolboxTools {
  status: ToolboxStatus;
  tools: ToolDescriptorView[];
}

export function useToolboxTools(): UseToolboxTools {
  const [status, setStatus] = useState<ToolboxStatus>("loading");
  const [tools, setTools] = useState<ToolDescriptorView[]>([]);
  const toast = useToast();

  useEffect(() => {
    let cancelled = false;
    void (async (): Promise<void> => {
      try {
        const { data, error } = await api.GET("/skills/toolbox", {});
        if (cancelled) return;
        if (error || !data) {
          setStatus("error");
          toast("工具箱加载失败，请重试。", "error");
          return;
        }
        setTools(data.tools ?? []);
        setStatus("ready");
      } catch {
        if (cancelled) return;
        setStatus("error");
        toast("工具箱加载异常，请检查网络。", "error");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [toast]);

  return { status, tools };
}
