"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { PlusCircle, ArrowUpRight, Zap, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { formatDate } from "@/lib/utils";
import { PLAN_LIMITS } from "@/lib/plan-limits";
import { jobsApi, userApi, type JobListItem, type PlanLimitsResponse } from "@/lib/api";
import { getValidToken } from "@/lib/auth-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`;
}

export default function DashboardPage() {
  const router = useRouter();
  const [jobs, setJobs] = useState<JobListItem[]>([]);
  const [limits, setLimits] = useState<PlanLimitsResponse | null>(null);
  const [userName, setUserName] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) { router.push("/login"); return; }
      try {
        const [jobsData, limitsData, userData] = await Promise.all([
          jobsApi.list(token),
          userApi.getLimits(token),
          userApi.getMe(token),
        ]);
        setJobs(jobsData);
        setLimits(limitsData);
        setUserName(userData.name);
      } catch {
        router.push("/login");
      } finally {
        setLoading(false);
      }
    })();
  }, [router]);

  const userPlan = limits?.plan ?? "free";
  const planKey = userPlan in PLAN_LIMITS ? userPlan : "free";
  const planConfig = PLAN_LIMITS[planKey];
  const videosToday = limits?.videos_used_today ?? 0;
  const videosPerDay = limits?.videos_per_day ?? planConfig.videos_per_day;
  const maxDurationMinutes = limits?.max_duration_minutes ?? planConfig.max_duration_minutes;
  const usagePct = videosPerDay >= 9999 || videosPerDay === Infinity
    ? 0
    : (videosToday / videosPerDay) * 100;

  const recentJobs = jobs.slice(0, 4);

  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 dashboard...
      </div>
    );
  }

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Overview</h1>
          <p className="text-zinc-500 text-sm mt-1">
            Welcome back{userName ? `, ${userName}` : ""}! Ready to find viral clips?
          </p>
        </div>
        <Link href="/dashboard/new-job">
          <Button className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0 shadow-lg shadow-violet-900/30">
            <PlusCircle className="w-4 h-4 mr-2" />
            New Job
          </Button>
        </Link>
      </div>

      <div className="grid md:grid-cols-3 gap-4 mb-8">
        {/* Plan status */}
        <div className="md:col-span-2 glass-card p-6 border border-violet-500/20">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-xs text-zinc-500 mb-1">Current Plan</div>
              <div className="flex items-center gap-2">
                <Badge className="bg-zinc-800 text-zinc-300 border-zinc-700 capitalize">
                  {planConfig.name}
                </Badge>
                {planKey === "free" && (
                  <Link href="/pricing">
                    <Badge className="bg-violet-500/15 text-violet-300 border-violet-500/30 cursor-pointer hover:bg-violet-500/25 transition-colors">
                      <Zap className="w-3 h-3 mr-1" />
                      Upgrade
                    </Badge>
                  </Link>
                )}
              </div>
            </div>
            <div className="text-right">
              <div className="text-2xl font-bold text-white">
                {videosToday}
                <span className="text-zinc-500 text-sm font-normal">
                  {" "}/ {videosPerDay >= 9999 || videosPerDay === Infinity ? "∞" : videosPerDay}
                </span>
              </div>
              <div className="text-xs text-zinc-500">Videos used today</div>
            </div>
          </div>
          <Progress value={usagePct} className="h-2 bg-white/10" />
          <div className="flex justify-between text-xs text-zinc-600 mt-1.5">
            <span>Resets at midnight IST</span>
            <span>Max {maxDurationMinutes >= 9999 || maxDurationMinutes === Infinity ? "unlimited" : maxDurationMinutes + "min"} per video</span>
          </div>
        </div>

        {/* Quick stat */}
        <div className="glass-card p-6">
          <div className="text-xs text-zinc-500 mb-1">Total Jobs</div>
          <div className="text-3xl font-bold text-white">{jobs.length}</div>
          <div className="text-xs text-zinc-500 mt-1">All time</div>
          <Link href="/dashboard/jobs" className="flex items-center gap-1 text-xs text-violet-400 hover:text-violet-300 mt-4 transition-colors">
            View history <ArrowUpRight className="w-3 h-3" />
          </Link>
        </div>
      </div>

      {/* Upgrade CTA for free plan */}
      {planKey === "free" && (
        <div className="glass-card p-5 mb-8 border border-violet-500/30 bg-violet-500/5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <div className="text-sm font-semibold text-white mb-0.5">Unlock more with Pro</div>
            <div className="text-xs text-zinc-400">
              5 videos/day · 20-min limit · No watermark · Priority processing
            </div>
          </div>
          <Link href="/pricing">
            <Button
              size="sm"
              className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0 whitespace-nowrap"
            >
              <Zap className="w-3.5 h-3.5 mr-1.5" />
              Upgrade to Pro — ₹799/mo
            </Button>
          </Link>
        </div>
      )}

      {/* Recent jobs */}
      <div className="glass-card overflow-hidden">
        <div className="px-5 py-4 border-b border-white/8 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-white">Recent Jobs</h2>
          <Link href="/dashboard/jobs" className="text-xs text-violet-400 hover:text-violet-300 transition-colors">
            View all →
          </Link>
        </div>
        {recentJobs.length === 0 ? (
          <div className="p-8 text-center text-zinc-500 text-sm">
            No jobs yet.{" "}
            <Link href="/dashboard/new-job" className="text-violet-400 hover:text-violet-300">
              Analyze your first video →
            </Link>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/5">
                  <th className="text-left px-5 py-3 text-xs font-medium text-zinc-500">Video</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-zinc-500">Duration</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-zinc-500">Status</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-zinc-500">Date</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-zinc-500"></th>
                </tr>
              </thead>
              <tbody>
                {recentJobs.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 text-white max-w-xs truncate">
                        {job.video_title ?? "Processing..."}
                      </div>
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400">{formatDuration(null)}</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-zinc-400 hover:text-white">
                            View Results
                          </Button>
                        </Link>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
