import { useSearchParams } from "next/navigation";
import { useEffect, useCallback, useState, useRef } from "react";
import { toast } from "sonner";

import { useI18n } from "@/core/i18n/hooks";
import {
  isSelectedSkillMessage,
  isSelectedSkillsMessage,
  type SelectedSkillPayloadItem,
} from "@/core/iframe-messages";
import { bootstrapRemoteSkill } from "@/core/skills/api";

/** 技能基础数据 */
interface SkillData {
  skill_id: string;
  title: string;
}

/** 错误信息状态 */
interface SkillError {
  title: string;
  message: string;
}

interface UseSelectedSkillListenerOptions {
  /** 当前会话 thread_id，用于调用 bootstrapRemoteSkill */
  threadId: string | null;
}

interface UseSelectedSkillListenerReturn {
  /** 当前选中的技能数据（用于 UI 展示，如 Badge） */
  selectedSkill: SkillData | null;
  /** 当前错误信息，不为 null 时展示 DevDialog */
  skillError: SkillError | null;
  /** 清除错误信息（关闭 DevDialog 时调用） */
  clearSkillError: () => void;
  /** 是否正在加载（处理 skill 中） */
  isBootstrapping: boolean;
}

/**
 * 监听宿主页通过 postMessage 发送的 selectedSkill 消息或 URL 中的 skill 参数，
 * 收到后自动调用 bootstrapRemoteSkill 接口：
 * - 成功：使用 toast 提示
 * - 失败：返回 skillError 供 DevDialog 显示
 */
export function useSelectedSkillListener({
  threadId,
}: UseSelectedSkillListenerOptions): UseSelectedSkillListenerReturn {
  const { t } = useI18n();
  const searchParams = useSearchParams();
  const [selectedSkill, setSelectedSkill] = useState<SkillData | null>(null);
  const [skillError, setSkillError] = useState<SkillError | null>(null);
  const [isBootstrapping, setIsBootstrapping] = useState(false);

  const isFirstLoadRef = useRef(false);
  const skillBootstrappedKeyRef = useRef<string | null>(null);

  const performBootstrap = useCallback(
    async (skills: SelectedSkillPayloadItem[], title: string) => {
      if (!threadId) return;
      const contentIds = Array.from(
        new Set(
          skills
            .map((skill) => Number(String(skill.id).trim()))
            .filter((id) => Number.isFinite(id) && id > 0),
        ),
      );
      if (contentIds.length === 0) {
        console.warn("[useSelectedSkillListener] 忽略非法 skill ids", skills);
        setSkillError({
          title: t.skills.loadFailedWithTitle(title),
          message: t.skills.invalidSkillIdArray,
        });
        return;
      }

      const languageTypeRaw =
        searchParams.get("languageType")?.trim() ??
        searchParams.get("language_type")?.trim();
      const languageType = languageTypeRaw ? Number(languageTypeRaw) : 0;

      const initKey = `${threadId}:${contentIds.join(",")}:${languageType}`;
      if (skillBootstrappedKeyRef.current === initKey) {
        return;
      }

      console.log(
        `[useSelectedSkillListener] 开始初始化技能: ${title} (${contentIds.join(",")})`,
      );
      setIsBootstrapping(true);
      toast.loading(t.skills.loading(title), { id: "skill-bootstrap" });

      try {
        const result = await bootstrapRemoteSkill({
          thread_id: threadId,
          content_ids: contentIds,
          language_type: languageType,
          target_dir: "/mnt/user-data/uploads/skill",
          clear_target: true,
        });

        toast.dismiss("skill-bootstrap");

        if (result.success) {
          skillBootstrappedKeyRef.current = initKey;
          toast.success(t.skills.loadSuccessWithTitle(title), {
            description:
              result.message || t.skills.createdFiles(result.created_files),
            duration: 4000,
          });
        } else {
          setSkillError({
            title: t.skills.loadFailedWithTitle(title),
            message: result.message || t.skills.unknownError,
          });
        }
      } catch (err) {
        toast.dismiss("skill-bootstrap");
        const message =
          err instanceof Error ? err.message : t.skills.networkRequestFailed;
        setSkillError({ title: t.skills.loadErrorWithTitle(title), message });
      } finally {
        setIsBootstrapping(false);
      }
    },
    [threadId, searchParams, t.skills],
  );

  // 1. URL 初始化集成
  useEffect(() => {
    if (!threadId || isFirstLoadRef.current) return;

    const skillIdFromQuery = searchParams.get("skill_id");
    const titleFromQuery = searchParams.get("title");
    if (skillIdFromQuery && titleFromQuery) {
      isFirstLoadRef.current = true;
      setSelectedSkill({ skill_id: skillIdFromQuery, title: titleFromQuery });
      void performBootstrap(
        [{ id: skillIdFromQuery, name: titleFromQuery }],
        titleFromQuery,
      );
    }
  }, [threadId, searchParams, performBootstrap]);

  const handleMessage = useCallback(
    (event: MessageEvent) => {
      if (isSelectedSkillMessage(event.data)) {
        const data = event.data;
        const { id, title } = data;
        console.log(
          "[useSelectedSkillListener] 收到 postMessage selectedSkill:",
          data,
        );
        setSelectedSkill({ skill_id: String(id), title });
        void performBootstrap([{ id, name: title }], title);
        return;
      }

      if (isSelectedSkillsMessage(event.data)) {
        const { selectedSkills } = event.data;
        if (!selectedSkills.length) return;
        const first = selectedSkills[0]!;
        const firstTitle = first.name;
        console.log(
          "[useSelectedSkillListener] 收到 postMessage selectedSkills:",
          event.data,
        );
        setSelectedSkill({ skill_id: String(first.id), title: firstTitle });
        void performBootstrap(selectedSkills, firstTitle);
      }
    },
    [performBootstrap],
  );

  useEffect(() => {
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, [handleMessage]);

  const clearSkillError = useCallback(() => setSkillError(null), []);

  return { selectedSkill, skillError, clearSkillError, isBootstrapping };
}
