<script setup>
import { Icon } from "@iconify/vue";
import { ParseResult, Schema } from "effect";
import { toast } from "vue-sonner";
import { Button } from "../button";
import { ButtonGroup } from "../button-group";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from "../dropdown-menu";
import {
  DOC_PROMPT_PREFIX,
  buildLlmUrl,
  schemaToJsonMarkdown
} from "../../../utils/config-clipboard";
defineOptions({ name: "ShwfedConfigToolbar", inheritAttrs: false });
const props = defineProps({
  schema: { type: null, required: true },
  getConfig: { type: Function, required: true }
});
const emit = defineEmits(["paste"]);
function makeDocMarkdown() {
  try {
    return schemaToJsonMarkdown(props.schema);
  } catch (err) {
    toast.error("\u751F\u6210\u914D\u7F6E\u6587\u6863\u5931\u8D25", {
      description: err instanceof Error ? err.message : String(err)
    });
    return null;
  }
}
async function copyDoc() {
  const md = makeDocMarkdown();
  if (md === null) return;
  try {
    await navigator.clipboard.writeText(md);
    toast.success("\u5DF2\u590D\u5236\u914D\u7F6E\u6587\u6863");
  } catch (err) {
    toast.error("\u590D\u5236\u5931\u8D25", {
      description: err instanceof Error ? err.message : String(err)
    });
  }
}
function openInLlm(provider) {
  const md = makeDocMarkdown();
  if (md === null) return;
  const url = buildLlmUrl(provider, `${DOC_PROMPT_PREFIX}

${md}`);
  window.open(url, "_blank", "noopener,noreferrer");
}
async function copyConfig() {
  try {
    const text = JSON.stringify(props.getConfig(), null, 2);
    await navigator.clipboard.writeText(text);
    toast.success("\u5DF2\u590D\u5236\u5F53\u524D\u914D\u7F6E");
  } catch (err) {
    toast.error("\u590D\u5236\u5931\u8D25", {
      description: err instanceof Error ? err.message : String(err)
    });
  }
}
async function pasteConfig() {
  let text;
  try {
    text = await navigator.clipboard.readText();
  } catch (err) {
    toast.error("\u8BFB\u53D6\u526A\u8D34\u677F\u5931\u8D25", {
      description: err instanceof Error ? err.message : String(err)
    });
    return;
  }
  let parsed;
  try {
    parsed = JSON.parse(text);
  } catch (err) {
    toast.error("\u526A\u8D34\u677F\u5185\u5BB9\u4E0D\u662F\u5408\u6CD5\u7684 JSON", {
      description: err instanceof Error ? err.message : String(err)
    });
    return;
  }
  const result = Schema.decodeUnknownEither(props.schema)(parsed);
  if (result._tag === "Left") {
    const issues = ParseResult.ArrayFormatter.formatErrorSync(result.left);
    const first = issues[0];
    const path = first?.path.map(String).join(".") ?? "";
    toast.error("\u914D\u7F6E\u6821\u9A8C\u5931\u8D25", {
      description: first ? path ? `${path}: ${first.message}` : first.message : "\u672A\u77E5\u9519\u8BEF"
    });
    return;
  }
  emit("paste", result.right);
  toast.success("\u5DF2\u4ECE\u526A\u8D34\u677F\u7C98\u8D34\u914D\u7F6E");
}
</script>

<template>
  <div class="flex items-center gap-2">
    <ButtonGroup>
      <Button
        size="sm"
        variant="default"
        @click="copyDoc"
      >
        <Icon icon="fluent:book-20-regular" />
        复制文档
      </Button>
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button
            size="sm"
            variant="default"
            aria-label="在 AI 对话中打开"
          >
            <Icon icon="fluent:chevron-down-20-regular" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem @select="openInLlm('claude')">
            <Icon icon="simple-icons:anthropic" />
            在 Claude 中打开
          </DropdownMenuItem>
          <DropdownMenuItem @select="openInLlm('chatgpt')">
            <Icon icon="simple-icons:openai" />
            在 ChatGPT 中打开
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </ButtonGroup>

    <ButtonGroup>
      <Button
        size="sm"
        variant="default"
        @click="copyConfig"
      >
        <Icon icon="fluent:clipboard-text-20-regular" />
        复制配置
      </Button>
      <Button
        size="sm"
        variant="default"
        @click="pasteConfig"
      >
        <Icon icon="fluent:clipboard-paste-20-regular" />
        粘贴配置
      </Button>
    </ButtonGroup>
  </div>
</template>
