"use client";

import { useRouter } from "next/navigation";
import {
  Users,
  Award,
  BarChart3,
  TrendingUp,
  Calendar,
  CheckCircle,
  XCircle,
  ArrowLeft,
  ClipboardList,
  Trophy,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { useAdminAnalytics } from "@/lib/api/hooks/useAdmin";

const GRADE_CONFIG: Record<string, { bg: string; text: string; border: string; bar: string }> = {
  A: { bg: "bg-green-500/20", text: "text-green-400", border: "border-green-500", bar: "bg-green-500" },
  B: { bg: "bg-blue-500/20", text: "text-blue-400", border: "border-blue-500", bar: "bg-blue-500" },
  C: { bg: "bg-yellow-500/20", text: "text-yellow-400", border: "border-yellow-500", bar: "bg-yellow-500" },
  D: { bg: "bg-orange-500/20", text: "text-orange-400", border: "border-orange-500", bar: "bg-orange-500" },
  F: { bg: "bg-red-500/20", text: "text-red-400", border: "border-red-500", bar: "bg-red-500" },
};

function GradeBadge({ grade }: { grade: string }) {
  const c = GRADE_CONFIG[grade] ?? GRADE_CONFIG.F;
  return (
    <span className={`px-2.5 py-1 rounded-full text-xs font-bold border ${c.bg} ${c.text} ${c.border}`}>
      {grade}
    </span>
  );
}

export default function AnalyticsPage() {
  const router = useRouter();
  const { data, isLoading, isError } = useAdminAnalytics();

  if (isLoading) {
    return (
      <div className="flex justify-center py-20">
        <Spinner className="size-8 text-blue-500" />
      </div>
    );
  }

  if (isError || !data) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4 text-center">
        <BarChart3 className="size-12 text-gray-600" />
        <p className="text-gray-400 text-lg">Failed to load analytics</p>
        <Button onClick={() => router.push("/admin")} variant="secondary">
          Back to Dashboard
        </Button>
      </div>
    );
  }

  const { overview, gradeDistribution, topPerformers, passFail, recentActivity } = data;

  // Total students who attempted (for grade distribution denominator)
  const totalAttempted = Object.values(gradeDistribution).reduce((sum, n) => sum + n, 0);

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Header */}
      <div className="p-6 sm:p-8 bg-gradient-to-r from-gray-900 to-black border border-gray-800 rounded-xl">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div>
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-white mb-1">
              Analytics &amp; Reports
            </h1>
            <p className="text-gray-400 text-sm sm:text-base">
              Comprehensive performance insights and statistics
            </p>
          </div>
          <Button
            onClick={() => router.push("/admin")}
            className="bg-gray-800 hover:bg-gray-700 text-white border border-gray-700"
          >
            <ArrowLeft className="size-4 mr-2" />
            Back to Dashboard
          </Button>
        </div>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
        <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-gray-800 rounded-xl border border-gray-700">
              <Users className="size-6 sm:size-8 text-white" />
            </div>
            <TrendingUp className="size-5 text-green-500" />
          </div>
          <p className="text-sm text-gray-400 mb-1">Total Students</p>
          <p className="text-3xl sm:text-4xl font-bold text-white">{overview.totalStudents}</p>
        </div>

        <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-gray-800 rounded-xl border border-gray-700">
              <Award className="size-6 sm:size-8 text-white" />
            </div>
            <TrendingUp className="size-5 text-green-500" />
          </div>
          <p className="text-sm text-gray-400 mb-1">Pass Rate</p>
          <p className="text-3xl sm:text-4xl font-bold text-white">{overview.passRate}%</p>
        </div>

        <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-gray-800 rounded-xl border border-gray-700">
              <BarChart3 className="size-6 sm:size-8 text-white" />
            </div>
            <span className="text-xs text-gray-400">Average</span>
          </div>
          <p className="text-sm text-gray-400 mb-1">Avg. Score</p>
          <p className="text-3xl sm:text-4xl font-bold text-white">{overview.averageScore}%</p>
        </div>

        <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-gray-800 rounded-xl border border-gray-700">
              <ClipboardList className="size-6 sm:size-8 text-white" />
            </div>
            <Calendar className="size-5 text-gray-400" />
          </div>
          <p className="text-sm text-gray-400 mb-1">Total Questions</p>
          <p className="text-3xl sm:text-4xl font-bold text-white">{overview.totalQuestions}</p>
        </div>
      </div>

      {/* Grade Distribution + Top Performers */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8">
        {/* Grade Distribution */}
        <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-6">Grade Distribution</h2>
          <div className="space-y-5">
            {(["A", "B", "C", "D", "F"] as const).map((grade) => {
              const count = gradeDistribution[grade] ?? 0;
              const pct = totalAttempted > 0 ? ((count / totalAttempted) * 100).toFixed(1) : "0.0";
              const cfg = GRADE_CONFIG[grade];
              return (
                <div key={grade}>
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-3">
                      <span className={`px-3 py-1 rounded-full text-sm font-bold border ${cfg.bg} ${cfg.text} ${cfg.border}`}>
                        Grade {grade}
                      </span>
                      <span className="text-white font-medium text-sm">
                        {count} {count === 1 ? "student" : "students"}
                      </span>
                    </div>
                    <span className="text-gray-400 text-sm">{pct}%</span>
                  </div>
                  <div className="w-full bg-gray-800 rounded-full h-3 overflow-hidden border border-gray-700">
                    <div
                      className={`${cfg.bar} h-full rounded-full transition-all duration-500`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Top Performers */}
        <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-6">Top Performers</h2>
          {topPerformers.length === 0 ? (
            <div className="text-center py-12">
              <Trophy className="size-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-500">No exam results yet</p>
            </div>
          ) : (
            <div className="space-y-4">
              {topPerformers.map((student, index) => (
                <div
                  key={student.id}
                  className="p-4 bg-gray-800 rounded-xl border border-gray-700 hover:border-gray-600 transition-colors"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className={`w-9 h-9 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-white shrink-0 ${
                        index === 0 ? "bg-yellow-500" :
                        index === 1 ? "bg-gray-400" :
                        index === 2 ? "bg-orange-600" :
                        "bg-gray-700"
                      }`}>
                        {index + 1}
                      </div>
                      <div className="min-w-0">
                        <p className="text-white font-medium text-sm sm:text-base truncate">{student.fullName}</p>
                        <p className="text-gray-400 text-xs sm:text-sm truncate">{student.email}</p>
                      </div>
                    </div>
                    <div className="text-right shrink-0 ml-3">
                      <p className="text-lg sm:text-xl font-bold text-white">{student.percentage}%</p>
                      <GradeBadge grade={student.grade} />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Pass/Fail Overview + Recent Activity */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8">
        {/* Pass/Fail Overview */}
        <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-6">Pass/Fail Overview</h2>
          <div className="space-y-6">
            <div className="p-5 bg-green-500/10 border border-green-500 rounded-xl">
              <div className="flex items-center justify-between mb-2">
                <p className="text-green-400 font-medium">Passed Students</p>
                <TrendingUp className="size-5 text-green-400" />
              </div>
              <p className="text-3xl sm:text-4xl font-bold text-white mb-1">{passFail.passed}</p>
              <p className="text-sm text-green-400">{passFail.passedPercentage}% of total</p>
            </div>

            <div className="p-5 bg-red-500/10 border border-red-500 rounded-xl">
              <div className="flex items-center justify-between mb-2">
                <p className="text-red-400 font-medium">Failed Students</p>
                <TrendingUp className="size-5 text-red-400 rotate-180" />
              </div>
              <p className="text-3xl sm:text-4xl font-bold text-white mb-1">{passFail.failed}</p>
              <p className="text-sm text-red-400">{passFail.failedPercentage}% of total</p>
            </div>
          </div>
        </div>

        {/* Recent Exam Activity */}
        <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl shadow-2xl">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-6">Recent Exam Activity</h2>
          {recentActivity.length === 0 ? (
            <div className="text-center py-12">
              <Calendar className="size-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-500">No recent activity</p>
            </div>
          ) : (
            <div className="space-y-3">
              {recentActivity.map((activity, i) => (
                <div
                  key={`${activity.id}-${i}`}
                  className="p-3 bg-gray-800 rounded-lg border border-gray-700 hover:border-gray-600 transition-colors"
                >
                  <div className="flex items-center justify-between gap-2">
                    <div className="min-w-0 flex-1">
                      <p className="text-white font-medium text-sm truncate">{activity.fullName}</p>
                      <p className="text-xs text-gray-400">{activity.submittedAt}</p>
                    </div>
                    <span className={`px-2.5 py-1 rounded-full text-xs font-bold shrink-0 border ${
                      activity.status === "Passed"
                        ? "bg-green-500/20 text-green-400 border-green-500"
                        : "bg-red-500/20 text-red-400 border-red-500"
                    }`}>
                      {activity.status}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
