"use client";

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

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

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

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

  const trigger = async (id: string) => {
    await fetch(`/cron/jobs/${id}/run`, { method: "POST" });
    load();
  };

  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">
        <div className="flex items-center gap-2">
          <Timer size={20} style={{ color: "#f59e0b" }} />
          <h1 className="text-xl font-bold" style={{ color: "#f59e0b" }}>Cron Jobs</h1>
        </div>
        <button
          onClick={load}
          className="p-2 rounded-xl active:scale-95 transition-all"
          style={{ color: "#f59e0b" }}
        >
          <RefreshCw size={16} />
        </button>
      </div>

      {loading ? (
        <div className="space-y-2">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="glass p-4 animate-pulse">
              <div className="h-4 bg-white/[0.06] rounded w-3/4 mb-2" />
              <div className="h-3 bg-white/[0.06] rounded w-1/2" />
            </div>
          ))}
        </div>
      ) : jobs.length === 0 ? (
        <div className="glass p-6 text-center text-sm text-zinc-500">
          No cron jobs configured
        </div>
      ) : (
        <div className="space-y-4">
          {active.length > 0 && (
            <Section label="Active" jobs={active} onTrigger={trigger} />
          )}
          {paused.length > 0 && (
            <Section label="Paused" jobs={paused} onTrigger={trigger} />
          )}
          {other.length > 0 && (
            <Section label="Other" jobs={other} onTrigger={trigger} />
          )}
        </div>
      )}
    </div>
  );
}

function Section({ label, jobs, onTrigger }: { label: string; jobs: CronJob[]; onTrigger: (id: string) => void }) {
  return (
    <div>
      <h2 className="text-xs font-medium text-zinc-500 uppercase tracking-wider mb-2 px-1">
        {label} ({jobs.length})
      </h2>
      <div className="space-y-1.5">
        {jobs.map((j) => (
          <CronCard key={j.id} job={j} onTrigger={() => onTrigger(j.id)} />
        ))}
      </div>
    </div>
  );
}

function CronCard({ job, onTrigger }: { job: CronJob; onTrigger: () => void }) {
  const isActive = job.status === "active" || job.status === "enabled";
  return (
    <div className="glass p-4">
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="flex-1 min-w-0">
          <div className="text-sm font-medium text-zinc-200 line-clamp-1">
            {job.name || job.prompt.slice(0, 60)}
          </div>
          <div className="text-xs text-zinc-500 font-mono mt-0.5">{job.schedule}</div>
        </div>
        <div className="flex items-center gap-1.5 shrink-0">
          <div
            className="w-2 h-2 rounded-full"
            style={{ background: isActive ? "#22c55e" : "#6b7280" }}
          />
          <button
            onClick={onTrigger}
            className="p-1.5 rounded-lg active:bg-white/[0.06]"
            style={{ color: "#f59e0b" }}
            title="Run now"
          >
            <Play size={14} />
          </button>
        </div>
      </div>
      <div className="flex items-center gap-3 text-[11px] text-zinc-500">
        <span>→ {job.deliver}</span>
        {job.skills && job.skills.length > 0 && (
          <span className="text-purple-400/60">{job.skills.join(", ")}</span>
        )}
        {job.last_run && <span className="ml-auto">last: {timeAgo(new Date(job.last_run).getTime() / 1000)}</span>}
      </div>
    </div>
  );
}
