"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { PlusCircle, Loader2 } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { jobsApi, type JobListItem } from "@/lib/api";
import { getValidToken } from "@/lib/auth-store";


export default function JobHistoryPage() {
  const router = useRouter();
  const [jobs, setJobs] = useState<JobListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) {
        router.push("/login");
        return;
      }
      try {
        const data = await jobsApi.list(token);
        setJobs(data);
      } catch (err: unknown) {
        setError(err instanceof Error ? err.message : "Failed to load jobs");
      } finally {
        setLoading(false);
      }
    })();
  }, [router]);

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Job History</h1>
          <p className="text-zinc-500 text-sm mt-1">
            {loading ? "Loading..." : `${jobs.length} jobs processed`}
          </p>
        </div>
        <Link href="/dashboard/new-job">
          <Button className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0">
            <PlusCircle className="w-4 h-4 mr-2" />
            New Job
          </Button>
        </Link>
      </div>

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

      {error && (
        <div className="glass-card p-6 text-center text-red-400 text-sm">{error}</div>
      )}

      {!loading && !error && jobs.length === 0 && (
        <div className="glass-card p-10 text-center">
          <p className="text-zinc-500 text-sm mb-4">No jobs yet. Start by analyzing a YouTube video.</p>
          <Link href="/dashboard/new-job">
            <Button className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0">
              <PlusCircle className="w-4 h-4 mr-2" />
              New Job
            </Button>
          </Link>
        </div>
      )}

      {!loading && jobs.length > 0 && (
        <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">Video</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>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500"></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">
                      <div className="text-sm font-medium 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">
                      <Badge
                        className={
                          job.status === "completed"
                            ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs"
                            : job.status === "processing" || job.status === "queued"
                            ? "bg-yellow-500/15 text-yellow-400 border-yellow-500/30 text-xs"
                            : "bg-red-500/15 text-red-400 border-red-500/30 text-xs"
                        }
                      >
                        {job.status}
                      </Badge>
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400">{formatDate(job.created_at)}</td>
                    <td className="px-5 py-4">
                      {job.status === "completed" && (
                        <Link href={`/dashboard/jobs/${job.id}`}>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="h-7 text-xs text-violet-400 hover:text-violet-300"
                          >
                            View Results →
                          </Button>
                        </Link>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
