"use client";

import { useCallback, useState } from "react";

import { api } from "@/lib/api/client";
import { useToast } from "@/components/Toast";
import { buildRefineRequest } from "./style";

export type RefineStatus = "idle" | "refining" | "done" | "error";

export interface RefineResult {
  original: string;
  refined: string;
}

export interface UseRefine {
  status: RefineStatus;
  result: RefineResult | null;
  // 回炉重写某段（可选改写指令）→ 返回 {original, refined} 或 null（失败）。
  refine: (
    projectId: string,
    chapterNo: number,
    segment: string,
    instruction?: string,
  ) => Promise<RefineResult | null>;
  reset: () => void;
}

function errorCode(error: unknown): string | undefined {
  if (typeof error !== "object" || error === null) return undefined;
  const env = error as { error?: { code?: unknown } };
  return typeof env.error?.code === "string" ? env.error.code : undefined;
}

// 回炉（POST .../refine）：同步返回新旧 diff，不写库（不变量#3）。
// 503 LLM_UNAVAILABLE（无凭据）优雅提示去设置；其余失败 toast。
export function useRefine(): UseRefine {
  const [status, setStatus] = useState<RefineStatus>("idle");
  const [result, setResult] = useState<RefineResult | null>(null);
  const toast = useToast();

  const refine = useCallback<UseRefine["refine"]>(
    async (projectId, chapterNo, segment, instruction) => {
      setStatus("refining");
      setResult(null);
      try {
        const { data, error } = await api.POST(
          "/projects/{project_id}/chapters/{chapter_no}/refine",
          {
            params: {
              path: { project_id: projectId, chapter_no: chapterNo },
            },
            body: buildRefineRequest(segment, instruction),
          },
        );
        if (error || !data) {
          setStatus("error");
          const code = errorCode(error);
          toast(
            code === "LLM_UNAVAILABLE"
              ? "未配置提供商，请先去设置页连一家。"
              : "回炉失败，请稍后重试。",
            "error",
          );
          return null;
        }
        const outcome: RefineResult = {
          original: data.original,
          refined: data.refined,
        };
        setResult(outcome);
        setStatus("done");
        return outcome;
      } catch {
        setStatus("error");
        toast("回炉请求异常，请检查网络。", "error");
        return null;
      }
    },
    [toast],
  );

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

  return { status, result, refine, reset };
}
