"use client";

import { useCallback, useState } from "react";

import { useToast } from "@/components/Toast";
import { api } from "@/lib/api/client";
import { generationErrorMessage } from "@/lib/generation/cards";
import type {
  ProjectPlanGenerateRequest,
  ProjectPlanView,
} from "@/lib/api/types";

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

export interface UseProjectPlan {
  status: ProjectPlanStatus;
  plan: ProjectPlanView | null;
  generate: (seed: ProjectPlanGenerateRequest) => Promise<void>;
  reset: () => void;
}

// AI 立项方案生成器：POST /skills/project-plan/generate → 结构化方案预览（不入库）。
// 向导阶段调用（project 未建）；种子门控在后端亦校验（缺 genre/logline → 422）。
export function useProjectPlan(): UseProjectPlan {
  const [status, setStatus] = useState<ProjectPlanStatus>("idle");
  const [plan, setPlan] = useState<ProjectPlanView | null>(null);
  const toast = useToast();

  const generate = useCallback<UseProjectPlan["generate"]>(
    async (seed) => {
      setStatus("generating");
      setPlan(null);
      try {
        const { data, error } = await api.POST(
          "/skills/project-plan/generate",
          { body: seed },
        );
        if (error || !data) {
          setStatus("error");
          toast(generationErrorMessage(error), "error");
          return;
        }
        setPlan(data);
        setStatus("done");
      } catch {
        setStatus("error");
        toast("生成请求异常，请检查网络。", "error");
      }
    },
    [toast],
  );

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

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