"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { formatDate } from "@/lib/utils";
import { adminApi, type AdminJobResponse } from "@/lib/api";
import { getAdminToken } from "@/lib/admin-store";

function formatDuration(seconds: number | null): string {
  if (!seconds) return "—";
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

function StatusBadge({ status }: { status: string }) {
  if (status === "completed")
    return <Badge className="bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs">Done</Badge>;
  if (status === "processing" || status === "queued")
    return <Badge className="bg-yellow-500/15 text-yellow-400 border-yellow-500/30 text-xs capitalize">{status}</Badge>;
  return <Badge className="bg-red-500/15 text-red-400 border-red-500/30 text-xs">Failed</Badge>;
}

export default function AdminJobsPage() {
  const router = useRouter();
  const [jobs, setJobs] = useState<AdminJobResponse[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const token = await getAdminToken();
      if (!token) { router.push("/admin-login"); return; }
      try {
        setJobs(await adminApi.getJobs(token));
      } catch {
        router.push("/admin-login");
      } finally {
        setLoading(false);
      }
    })();
  }, [router]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" /> Loading jobs...
      </div>
    );
  }

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Video Jobs</h1>
        <p className="text-zinc-500 text-sm mt-1">{jobs.length} recent jobs</p>
      </div>

      <div className="glass-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/8">
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">#</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">User</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Video</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Duration</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Status</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Date</th>
              </tr>
            </thead>
            <tbody>
              {jobs.map((job) => (
                <tr key={job.id} className="border-b border-white/5 hover:bg-white/3 transition-colors">
                  <td className="px-5 py-4 text-xs font-mono text-zinc-600">#{job.id}</td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{job.user_email}</td>
                  <td className="px-5 py-4">
                    <div className="text-sm text-white max-w-xs truncate">
                      {job.video_title ?? "Processing..."}
                    </div>
                    <div className="text-xs text-zinc-600 font-mono truncate max-w-xs">
                      {job.youtube_url}
                    </div>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{formatDuration(job.duration_seconds)}</td>
                  <td className="px-5 py-4">
                    <StatusBadge status={job.status} />
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{formatDate(job.created_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {jobs.length === 0 && (
          <div className="p-8 text-center text-zinc-500 text-sm">No jobs yet.</div>
        )}
      </div>
    </div>
  );
}
