import { useEffect, useState } from "react";
import { useLoaderData } from "react-router";
import Navbar from "../../components/Navbar";

export const meta = () => [{ title: "Job Detail - AITrader" }];

export async function loader({ params, request }: { params: { jobId: string }; request: Request }) {
  const jobId = params.jobId;
  if (!jobId) return Response.json({ error: "jobId required" }, { status: 400 });
  const reqUrl = new URL(request.url);
  const host = request.headers.get("host") || reqUrl.host;
  const protocol = reqUrl.protocol;
  const baseUrl = `${protocol}//${host}`;

  try {
    const res = await fetch(`${baseUrl}/api/jobs/${jobId}`);
    const body = res.ok ? await res.json() : null;
    return Response.json(body);
  } catch (err) {
    console.error("/jobs loader error:", err);
    return Response.json({ error: "internal" }, { status: 500 });
  }
}

export default function JobDetail() {
  const initial = useLoaderData() as any;
  const [job, setJob] = useState<any>(initial);

  useEffect(() => {
    let cancelled = false;
    const poll = async () => {
      try {
        const id = job?.id || initial?.id;
        if (!id) return;
        const res = await fetch(`/api/jobs/${id}`);
        if (!res.ok) return;
        const j = await res.json();
        if (cancelled) return;
        setJob(j);
        if (j.state === "completed" || j.state === "failed") return;
      } catch (e) {
        // ignore
      }
      setTimeout(poll, 3000);
    };
    poll();
    return () => { cancelled = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50">
      <Navbar />
      <div className="mx-auto max-w-4xl px-6 py-8">
        <h1 className="text-2xl font-bold text-gray-900 mb-4">Job {job?.id}</h1>
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
          <div className="mb-3 text-sm text-gray-700">State: <strong className="ml-2">{job?.state}</strong></div>
          {job?.failedReason && (
            <div className="mb-3 text-red-600">Failed: {job.failedReason}</div>
          )}

          <div className="flex items-center gap-3 mb-3">
            {job?.state === 'waiting' || job?.state === 'queued' ? (
              <button
                onClick={async () => {
                  try {
                    const res = await fetch(`/api/jobs/${job?.id}/cancel`, { method: 'POST' });
                    if (res.ok) {
                      const d = await res.json();
                      if (d.cancelled) {
                        setJob((prev: any) => ({ ...(prev || {}), state: 'failed', failedReason: 'cancelled' }));
                      }
                    }
                  } catch (e) {
                    // ignore
                  }
                }}
                className="text-sm text-red-600 hover:underline"
              >
                Cancel Job
              </button>
            ) : null}

            <a href={`/api/jobs/${job?.id}`} target="_blank" rel="noreferrer" className="text-sm text-blue-600 hover:underline">Open API</a>
          </div>

          <div className="text-sm text-gray-700 mb-3">Data:</div>
          <pre className="bg-gray-50 p-3 rounded text-xs overflow-x-auto">{JSON.stringify(job?.data || job?.returnValue || job, null, 2)}</pre>

          <div className="mt-4">
            
          </div>
        </div>
      </div>
    </div>
  );
}
