"use client";

import { use, useState, useEffect } from "react";
import { ArrowLeft, Play, RefreshCw, Loader2 } from "lucide-react";
import Link from "next/link";
import { timeAgo } from "@/lib/utils";

interface CronJob {
  id: string;
  name?: string;
  prompt: string;
  schedule: string;
  status: string;
  deliver: string;
  skill?: string;
  skills?: string[];
  model?: string;
  repeat?: number;
  run_count?: number;
  last_run?: string;
  next_run?: string;
  created_at?: string;
}

interface CronOutput {
  timestamp: string;
  content: string;
}

export default function CronDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [job, setJob] = useState<CronJob | null>(null);
  const [outputs, setOutputs] = useState<CronOutput[]>([]);
  const [loading, setLoading] = useState(true);
  const [triggering, setTriggering] = useState(false);

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch("/cron/jobs/" + id).then((r) => r.json()).catch(() => null),
      fetch("/cron/jobs/" + id + "/output").then((r) => r.json()).catch(() => ({ outputs: [] })),
    ]).then(([jobData, outputData]) => {
      setJob(jobData?.job || jobData || null);
      setOutputs(outputData?.outputs || []);
    }).finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, [id]);

  const trigger = async () => {
    setTriggering(true);
    await fetch("/cron/jobs/" + id + "/run", { method: "POST" });
    setTriggering(false);
    setTimeout(load, 2000);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <Link href="/cron" className="p-1 -ml-1 rounded-lg active:bg-white/[0.04]">
          <ArrowLeft size={20} style={{ color: "var(--text-2)" }} />
        </Link>
        <div className="flex-1 min-w-0">
          <div className="text-[15px] font-medium truncate" style={{ color: "var(--text-1)" }}>
            {job?.name || job?.prompt?.slice(0, 40) || id}
          </div>
          {job && (
            <div className="text-[12px] font-mono mt-0.5" style={{ color: "var(--text-3)" }}>
              {job.schedule} → {job.deliver}
            </div>
          )}
        </div>
        <button onClick={load} className="p-1.5 rounded-lg active:bg-white/[0.04]" style={{ color: "var(--text-2)" }}>
          <RefreshCw size={16} />
        </button>
        <button
          onClick={trigger}
          disabled={triggering}
          className="p-1.5 rounded-lg active:bg-white/[0.04] disabled:opacity-30"
          style={{ color: "var(--accent)" }}
        >
          {triggering ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}
        </button>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[...Array(2)].map((_, i) => (
            <div key={i} className="card p-4 animate-pulse">
              <div className="h-4 rounded w-3/4 mb-2" style={{ background: "var(--bg-hover)" }} />
              <div className="h-3 rounded w-1/2" style={{ background: "var(--bg-hover)" }} />
            </div>
          ))}
        </div>
      ) : (
        <>
          {/* Job details */}
          {job && (
            <div className="card p-4 space-y-2">
              <div className="section-label mb-2">Details</div>
              <Row label="Status" value={job.status} />
              <Row label="Schedule" value={job.schedule} />
              <Row label="Deliver" value={job.deliver} />
              {job.model && <Row label="Model" value={job.model} />}
              {job.skills && job.skills.length > 0 && <Row label="Skills" value={job.skills.join(", ")} />}
              {job.run_count != null && <Row label="Runs" value={String(job.run_count)} />}
              {job.last_run && <Row label="Last run" value={timeAgo(new Date(job.last_run).getTime() / 1000)} />}
              {job.next_run && <Row label="Next run" value={new Date(job.next_run).toLocaleString()} />}
            </div>
          )}

          {/* Prompt */}
          {job?.prompt && (
            <div className="card p-4">
              <div className="section-label mb-2">Prompt</div>
              <p className="text-[13px] whitespace-pre-wrap leading-relaxed" style={{ color: "var(--text-1)" }}>
                {job.prompt}
              </p>
            </div>
          )}

          {/* Outputs */}
          <div>
            <div className="section-label mb-2">Output History ({outputs.length})</div>
            {outputs.length === 0 ? (
              <p className="text-sm py-6 text-center" style={{ color: "var(--text-3)" }}>No outputs yet</p>
            ) : (
              <div className="space-y-2">
                {outputs.map((o, i) => (
                  <div key={i} className="card p-4">
                    <div className="text-[11px] mb-2" style={{ color: "var(--text-3)" }}>
                      {new Date(o.timestamp).toLocaleString()}
                    </div>
                    <pre className="text-[13px] whitespace-pre-wrap leading-relaxed overflow-x-auto" style={{ color: "var(--text-1)" }}>
                      {o.content}
                    </pre>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex justify-between text-[13px]">
      <span style={{ color: "var(--text-2)" }}>{label}</span>
      <span className="font-mono truncate ml-4 max-w-[60%] text-right" style={{ color: "var(--text-1)" }}>{value}</span>
    </div>
  );
}
