import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from "react";
import type { Job } from "../domain/types";
import { useAuth } from "../auth/AuthContext";
import { isJobLiveActive } from "../lib/jobLabels";
import { useRepos } from "./DataContext";

type JobLiveValue = {
  /** 最近一次 list 的全部任務 */
  jobs: Job[];
  /**
   * 需即時關注的任務（running，或已到期的 pending/queued）。
   * 遠期排程（如 30 天後 token 延長）不進頂欄，但在任務列表仍可見。
   */
  activeJobs: Job[];
  /** 手動立刻拉一次 */
  reload: () => Promise<void>;
  /** 每次任務指紋變更遞增（鈴鐺／頁面可訂閱） */
  revision: number;
};

const JobLiveContext = createContext<JobLiveValue | null>(null);

function fingerprint(list: Job[]): string {
  return list
    .map(
      (j) =>
        `${j.id}:${j.status}:${j.progress_percent}:${j.progress_summary}:${j.updated_at}:${j.error ?? ""}`,
    )
    .join("|");
}

/**
 * 全域任務輪詢（所有模板共用）：
 * - 有 live-active 時 1.5s
 * - 否則 5s
 * 進度一變就 bump revision，鈴鐺／任務頁／人設頁不需手動重整。
 */
export function JobLiveProvider({ children }: { children: ReactNode }) {
  const repos = useRepos();
  const { member } = useAuth();
  const [jobs, setJobs] = useState<Job[]>([]);
  const [revision, setRevision] = useState(0);
  const fpRef = useRef("");
  const mounted = useRef(true);

  const reload = useCallback(async () => {
    if (!member) {
      setJobs([]);
      return;
    }
    try {
      // 只輪詢「執行中」分桶，避免一次拉全歷史
      const res = await repos.jobs.list({ tab: "active", page: 1, pageSize: 50 });
      if (!mounted.current) return;
      const list = res.list;
      setJobs(list);
      const fp = fingerprint(list);
      if (fp !== fpRef.current) {
        fpRef.current = fp;
        setRevision((r) => r + 1);
      }
    } catch {
      /* 未授權或暫時失敗：不刷掉既有列表 */
    }
  }, [repos.jobs, member]);

  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);

  const hasLiveActive = useMemo(() => jobs.some((j) => isJobLiveActive(j)), [jobs]);

  useEffect(() => {
    if (!member) {
      setJobs([]);
      fpRef.current = "";
      return;
    }
    void reload();
    const ms = hasLiveActive ? 1500 : 5000;
    const id = window.setInterval(() => {
      void reload();
    }, ms);
    return () => window.clearInterval(id);
  }, [member, reload, hasLiveActive]);

  const activeJobs = useMemo(() => jobs.filter((j) => isJobLiveActive(j)), [jobs]);

  const value = useMemo(
    () => ({ jobs, activeJobs, reload, revision }),
    [jobs, activeJobs, reload, revision],
  );

  return <JobLiveContext.Provider value={value}>{children}</JobLiveContext.Provider>;
}

export function useJobLive(): JobLiveValue {
  const ctx = useContext(JobLiveContext);
  if (!ctx) {
    return {
      jobs: [],
      activeJobs: [],
      reload: async () => {},
      revision: 0,
    };
  }
  return ctx;
}

/** 依人設 id 找進行中／最近的分析 job */
export function findPersonaAnalyzeJob(jobs: Job[], personaId: string | undefined): Job | null {
  if (!personaId) return null;
  const related = jobs.filter(
    (j) =>
      j.ref_id === personaId &&
      (j.template_type === "persona_analyze_account" ||
        j.template_type === "persona_analyze_text"),
  );
  if (related.length === 0) return null;
  const active = related.find((j) => isJobLiveActive(j));
  if (active) return active;
  return related.slice().sort((a, b) => b.updated_at - a.updated_at)[0] ?? null;
}
