import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { creativeApi, type PromptPreset } from "@/api/creative";
import { apiError } from "@/api/http";
import { useToastStore } from "@/stores/toast";

const promptTypes = [
  "剧本反推",
  "剧本分析",
  "剧本解析",
  "角色、场景、道具解析",
  "角色生成",
  "场景生成",
  "道具生成",
  "分镜图生成",
  "首尾帧生成",
  "视频生成",
];
export const premiumDramaPromptTypes = ["角色生成", "场景生成", "道具生成", "视频生成"] as const;

export function useModelPrompts() {
  const toast = useToastStore();
  const prompts = ref<PromptPreset[]>([]);
  const promptSelections = ref<Record<string, string>>({});

  async function loadPrompts(types: readonly string[] = promptTypes) {
    try {
      const results = await Promise.all(types.map((type) => creativeApi.promptPresets(type)));
      const merged = new Map<string, PromptPreset>();
      const selected: Record<string, string> = {};
      results.forEach((result, index) => {
        (result.prompts || []).forEach((prompt) => merged.set(prompt.id, prompt));
        if (result.selected_id) selected[types[index]] = result.selected_id;
      });
      prompts.value = [...merged.values()];
      promptSelections.value = selected;
    } catch (error) {
      prompts.value = [];
      promptSelections.value = {};
      showError(error, "加载提示词失败");
    }
  }

  async function selectPrompt(payload: { type: string; promptId: string }) {
    try {
      await creativeApi.selectPrompt(payload.type, payload.promptId);
      promptSelections.value = { ...promptSelections.value, [payload.type]: payload.promptId };
    } catch (error) {
      showError(error, "启用提示词失败");
    }
  }

  async function createPrompt(payload: { name: string; type: string; content: string }) {
    try {
      const saved = await creativeApi.createCustomPrompt(payload);
      prompts.value = [...prompts.value, saved];
      await creativeApi.selectPrompt(payload.type, saved.id);
      promptSelections.value = { ...promptSelections.value, [payload.type]: saved.id };
    } catch (error) {
      showError(error, "保存自定义提示词失败");
    }
  }

  async function updatePrompt(payload: { id: string; name: string; type: string; content: string }) {
    try {
      const saved = await creativeApi.updateCustomPrompt(payload.id, payload);
      prompts.value = prompts.value.map((item) => (item.id === saved.id ? saved : item));
    } catch (error) {
      showError(error, "保存提示词失败");
    }
  }

  async function deletePrompt(prompt: PromptPreset) {
    try {
      await ElMessageBox.confirm("删除后不可恢复，确定删除该提示词吗？", "删除提示词", {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      });
      await creativeApi.deleteCustomPrompt(prompt.id);
      prompts.value = prompts.value.filter((item) => item.id !== prompt.id);
      if (promptSelections.value[prompt.type] === prompt.id) {
        promptSelections.value = { ...promptSelections.value, [prompt.type]: "" };
      }
    } catch (error) {
      if (error !== "cancel" && error !== "close") showError(error, "删除提示词失败");
    }
  }

  function showError(error: unknown, title: string) {
    const detail = apiError(error);
    toast.error(detail.message, detail.copyText, title);
  }

  return { prompts, promptSelections, loadPrompts, selectPrompt, createPrompt, updatePrompt, deletePrompt };
}
