"use client";

import { useCallback, useState } from "react";

import { api } from "@/lib/api/client";
import { useToast } from "@/components/Toast";
import type { WorldEntityCardView } from "@/lib/api/types";
import { buildWorldGenerateRequest, generationErrorMessage } from "./cards";

export type WorldGenStatus = "idle" | "generating" | "done" | "error";

export interface UseWorldGen {
  status: WorldGenStatus;
  entities: WorldEntityCardView[];
  generate: (projectId: string, brief: string) => Promise<void>;
  reset: () => void;
}

// 世界观设计器：POST /world/generate → 预览实体（不入库）。
export function useWorldGen(): UseWorldGen {
  const [status, setStatus] = useState<WorldGenStatus>("idle");
  const [entities, setEntities] = useState<WorldEntityCardView[]>([]);
  const toast = useToast();

  const generate = useCallback<UseWorldGen["generate"]>(
    async (projectId, brief) => {
      setStatus("generating");
      setEntities([]);
      try {
        const { data, error } = await api.POST(
          "/projects/{project_id}/world/generate",
          {
            params: { path: { project_id: projectId } },
            body: buildWorldGenerateRequest(brief),
          },
        );
        if (error || !data) {
          setStatus("error");
          toast(generationErrorMessage(error), "error");
          return;
        }
        setEntities(data.entities ?? []);
        setStatus("done");
      } catch {
        setStatus("error");
        toast("生成请求异常，请检查网络。", "error");
      }
    },
    [toast],
  );

  const reset = useCallback((): void => {
    setStatus("idle");
    setEntities([]);
  }, []);

  return { status, entities, generate, reset };
}
