import { useQuery } from "@tanstack/react-query";
import { CheckCircle2, XCircle } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Progress } from "@/components/ui/progress";
import { DownloadButton } from "./blocks";
import { getJob } from "@/api/ops";

/** Polls a job. A result whose href is an API path ("/projects/…") gets a download button. */
export function JobProgress({
  jobId,
  title,
  onDone,
}: {
  jobId: string;
  title: string;
  onDone?: () => void;
}) {
  const started = useRef(Date.now());
  const [now, setNow] = useState(Date.now());
  const q = useQuery({
    queryKey: ["jobs", jobId],
    queryFn: () => getJob(jobId),
    refetchInterval: (qq) =>
      qq.state.data?.status === "done" || qq.state.data?.status === "failed" ? false : 1500,
  });
  const job = q.data;
  const doneRef = useRef(false);
  useEffect(() => {
    const i = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(i);
  }, []);
  useEffect(() => {
    if (job?.status === "done" && !doneRef.current) {
      doneRef.current = true;
      onDone?.();
    }
  }, [job?.status, onDone]);
  if (job?.status === "done")
    return (
      <div
        className="flex items-center gap-2 rounded-lg border border-success/30 bg-success-soft p-3 text-success"
        role="status"
      >
        <CheckCircle2 className="h-4 w-4" />{" "}
        <span className="font-medium">
          {title}: {job.result?.message}
        </span>
        {job.result?.href?.startsWith("/") && (
          <span className="ml-auto">
            <DownloadButton path={job.result.href}>Download</DownloadButton>
          </span>
        )}
      </div>
    );
  if (job?.status === "failed")
    return (
      <div
        className="flex items-center gap-2 rounded-lg bg-danger-soft p-3 text-danger"
        role="alert"
      >
        <XCircle className="h-4 w-4" /> {job.error}
      </div>
    );
  return (
    <div className="rounded-lg border bg-surface-2/60 p-3" aria-live="polite">
      <div className="flex justify-between text-[13px]">
        <span className="font-semibold">{title}</span>
        <span className="tabular text-muted-foreground">
          {Math.round((now - started.current) / 1000)} s
        </span>
      </div>
      <Progress value={job?.progressPct ?? 0} className="mt-2 h-1.5" />
      <p className="mt-1.5 text-[12px] text-muted-foreground">
        {job?.progressNote ?? "Queued…"} · You can leave this page — we'll notify you.
      </p>
    </div>
  );
}
