"use client";

import { useState, useEffect } from "react";
import { Timer, Play, RefreshCw } from "lucide-react";
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;
}

export default function CronPage() {
  const [jobs, setJobs] = useState<CronJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [triggering, setTriggering] = useState<string | null>(null);

  const load = () => {
    setLoading(true);
    fetch("/cron/jobs")
      .then((r) => r.json())
      .then((d) => setJobs(d.jobs || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  };

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

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

  const active = jobs.filter((j) => j.status === "active" || j.status === "enabled");
  const paused = jobs.filter((j) => j.status === "paused");
  const other = jobs.filter((j) => !["active", "enabled", "paused"].includes(j.status));

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold" style={{ color: "var(--text-1)" }}>Cron Jobs</h1>
        <button onClick={load} className="p-2 rounded-xl active:scale-95" style={{ color: "var(--text-2)" }}>
          <RefreshCw size={16} />
        </button>
      </div>

      {loading ? (
        <div className="space-y-2">
          {[...Array(3)].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>
      ) : jobs.length === 0 ? (
        <div className="py-12 text-center">
          <Timer size={32} className="mx-auto mb-3" style={{ color: "var(--text-3)" }} />
          <p className="text-sm" style={{ color: "var(--text-3)" }}>No cron jobs</p>
        </div>
      ) : (
        <div className="space-y-5">
          {active.length > 0 && <JobSection label="Active" jobs={active} onTrigger={trigger} triggering={triggering} />}
          {paused.length > 0 && <JobSection label="Paused" jobs={paused} onTrigger={trigger} triggering={triggering} />}
          {other.length > 0 && <JobSection label="Other" jobs={other} onTrigger={trigger} triggering={triggering} />}
        </div>
      )}
    </div>
  );
}

function JobSection({ label, jobs, onTrigger, triggering }: { label: string; jobs: CronJob[]; onTrigger: (id: string) => void; triggering: string | null }) {
  return (
    <div>
      <div className="section-label mb-2">{label} ({jobs.length})</div>
      <div className="space-y-2">
        {jobs.map((j) => (
          <div key={j.id} className="card p-4">
            <div className="flex items-start justify-between gap-2 mb-2">
              <div className="flex-1 min-w-0">
                <div className="text-[14px] line-clamp-1" style={{ color: "var(--text-1)" }}>
                  {j.name || j.prompt.slice(0, 60)}
                </div>
                <div className="text-[12px] font-mono mt-0.5" style={{ color: "var(--text-3)" }}>{j.schedule}</div>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <div
                  className="w-2 h-2 rounded-full"
                  style={{ background: j.status === "active" || j.status === "enabled" ? "#34c759" : "var(--text-3)" }}
                />
                <button
                  onClick={() => onTrigger(j.id)}
                  disabled={triggering === j.id}
                  className="p-1.5 rounded-lg active:bg-white/[0.04] disabled:opacity-30"
                  style={{ color: "var(--accent)" }}
                >
                  <Play size={14} />
                </button>
              </div>
            </div>
            <div className="flex items-center gap-3 text-[11px]" style={{ color: "var(--text-3)" }}>
              <span>→ {j.deliver}</span>
              {j.skills && j.skills.length > 0 && (
                <span style={{ color: "var(--accent)", opacity: 0.6 }}>{j.skills.join(", ")}</span>
              )}
              {j.last_run && <span className="ml-auto">last: {timeAgo(new Date(j.last_run).getTime() / 1000)}</span>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
