"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Users, CreditCard, Video, TrendingUp, Clock, Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
// Badge used in Recent Jobs status labels below
import { formatDate } from "@/lib/utils";
import { adminApi, type AdminStatsResponse, type AdminJobResponse } from "@/lib/api";
import { getAdminToken } from "@/lib/admin-store";

export default function AdminDashboard() {
  const router = useRouter();
  const [stats, setStats] = useState<AdminStatsResponse | null>(null);
  const [recentJobs, setRecentJobs] = useState<AdminJobResponse[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const token = await getAdminToken();
      if (!token) { router.push("/admin-login"); return; }
      try {
        const [s, jobs] = await Promise.all([
          adminApi.getStats(token),
          adminApi.getJobs(token),
        ]);
        setStats(s);
        setRecentJobs(jobs.slice(0, 4));
      } catch {
        router.push("/admin-login");
      } finally {
        setLoading(false);
      }
    })();
  }, [router]);

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

  const statCards = [
    {
      label: "Total Users",
      value: stats.total_users.toLocaleString(),
      sub: `${stats.admin_users} admin${stats.admin_users !== 1 ? "s" : ""}`,
      icon: Users,
      color: "text-violet-400",
      bg: "bg-violet-500/10",
      border: "border-violet-500/20",
    },
    {
      label: "Pro + Pro Max",
      value: (stats.pro_users + stats.pro_max_users).toLocaleString(),
      sub: `${stats.free_users} on free`,
      icon: CreditCard,
      color: "text-cyan-400",
      bg: "bg-cyan-500/10",
      border: "border-cyan-500/20",
    },
    {
      label: "Jobs Today",
      value: stats.jobs_today.toLocaleString(),
      sub: `${stats.jobs_processing} processing`,
      icon: Video,
      color: "text-emerald-400",
      bg: "bg-emerald-500/10",
      border: "border-emerald-500/20",
    },
    {
      label: "Total Jobs",
      value: stats.total_jobs.toLocaleString(),
      sub: "all time",
      icon: TrendingUp,
      color: "text-orange-400",
      bg: "bg-orange-500/10",
      border: "border-orange-500/20",
    },
  ];

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Dashboard</h1>
        <p className="text-zinc-500 text-sm mt-1">Welcome back. Here&apos;s what&apos;s happening.</p>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
        {statCards.map((stat, i) => (
          <div key={i} className={`glass-card p-5 border ${stat.border}`}>
            <div className="flex items-center justify-between mb-3">
              <div className={`w-9 h-9 rounded-lg ${stat.bg} border ${stat.border} flex items-center justify-center`}>
                <stat.icon className={`w-4 h-4 ${stat.color}`} />
              </div>
            </div>
            <div className="text-2xl font-bold text-white">{stat.value}</div>
            <div className="text-xs text-zinc-500 mt-0.5">{stat.label}</div>
            {stat.sub && <div className="text-[10px] text-zinc-600 mt-0.5">{stat.sub}</div>}
          </div>
        ))}
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Plan breakdown */}
        <div className="lg:col-span-2 glass-card p-6">
          <h2 className="text-sm font-semibold text-white mb-6">User Plan Breakdown</h2>
          <div className="space-y-4">
            {[
              { label: "Free", count: stats.free_users, total: stats.total_users, color: "bg-zinc-500" },
              { label: "Pro", count: stats.pro_users, total: stats.total_users, color: "bg-violet-500" },
              { label: "Pro Max", count: stats.pro_max_users, total: stats.total_users, color: "bg-cyan-500" },
            ].map((row) => (
              <div key={row.label}>
                <div className="flex justify-between text-xs mb-1.5">
                  <span className="text-zinc-400">{row.label}</span>
                  <span className="text-zinc-300">{row.count.toLocaleString()}</span>
                </div>
                <div className="h-2 bg-white/10 rounded-full overflow-hidden">
                  <div
                    className={`h-full ${row.color} rounded-full`}
                    style={{ width: row.total ? `${(row.count / row.total) * 100}%` : "0%" }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="glass-card p-6">
          <h2 className="text-sm font-semibold text-white mb-4">Recent Jobs</h2>
          {recentJobs.length === 0 ? (
            <p className="text-xs text-zinc-500">No jobs yet.</p>
          ) : (
            <div className="space-y-3">
              {recentJobs.map((job) => (
                <div key={job.id} className="flex items-start gap-3">
                  <div className="w-7 h-7 rounded-full bg-violet-600/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <Clock className="w-3 h-3 text-violet-400" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-xs text-zinc-300 truncate">{job.user_email}</p>
                    <p className="text-xs text-zinc-600 truncate">{(job.video_title ?? job.youtube_url).slice(0, 30)}…</p>
                    <p className="text-[10px] text-zinc-700 mt-0.5">{formatDate(job.created_at)}</p>
                  </div>
                  <Badge
                    className={`ml-auto flex-shrink-0 text-[10px] px-1.5 py-0.5 ${
                      job.status === "completed"
                        ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30"
                        : job.status === "processing" || job.status === "queued"
                        ? "bg-yellow-500/15 text-yellow-400 border-yellow-500/30"
                        : "bg-red-500/15 text-red-400 border-red-500/30"
                    }`}
                  >
                    {job.status}
                  </Badge>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
