"use client";

import { useState } from "react";
import { useRouter, useParams } from "next/navigation";
import {
  ArrowLeft,
  BookOpen,
  Clock,
  ClipboardList,
  Users,
  TrendingUp,
  TrendingDown,
  BarChart3,
  CheckCircle,
  XCircle,
  FileEdit,
  Award,
  Calendar,
  Layers,
  Target,
  X,
  Trophy,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Modal } from "@/components/ui/modal";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useExamResults, useExamDetail } from "@/lib/api/hooks/useExam";
import type { ExamStudentResult, ExamQuestion } from "@/types/api";
import type { LucideIcon } from "lucide-react";

// ── Stat Card (clickable) ────────────────────────────────────

function StatCard({
  icon: Icon,
  gradient,
  label,
  value,
  subtext,
  onClick,
}: {
  icon: LucideIcon;
  gradient: string;
  label: string;
  value: string | number;
  subtext?: string;
  onClick?: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className={`p-4 sm:p-5 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl ${
        onClick ? "cursor-pointer hover:border-gray-600 transition-colors" : ""
      }`}
    >
      <div className="flex items-center gap-3 mb-3">
        <div className={`p-2 bg-gradient-to-br ${gradient} rounded-lg`}>
          <Icon className="size-4 text-white" />
        </div>
        <p className="text-gray-400 text-xs sm:text-sm">{label}</p>
      </div>
      <p className="text-xl sm:text-2xl font-bold text-white">{value}</p>
      {subtext && <p className="text-gray-500 text-xs mt-0.5">{subtext}</p>}
    </div>
  );
}

// ── Badges ───────────────────────────────────────────────────

function GradeBadge({ grade }: { grade: string }) {
  const colors: Record<string, string> = {
    A: "bg-green-500/20 text-green-400 border-green-500",
    B: "bg-blue-500/20 text-blue-400 border-blue-500",
    C: "bg-yellow-500/20 text-yellow-400 border-yellow-500",
    D: "bg-orange-500/20 text-orange-400 border-orange-500",
  };
  const c = colors[grade] ?? "bg-red-500/20 text-red-400 border-red-500";
  return (
    <span className={`px-2.5 py-1 rounded-full text-xs font-bold border ${c}`}>
      {grade}
    </span>
  );
}

function StatusBadge({ status }: { status: "Passed" | "Failed" }) {
  const passed = status === "Passed";
  return (
    <span
      className={`px-2.5 py-1 rounded-full text-xs font-semibold inline-flex items-center gap-1 ${
        passed
          ? "bg-green-500/20 text-green-400 border border-green-500"
          : "bg-red-500/20 text-red-400 border border-red-500"
      }`}
    >
      {passed ? <CheckCircle className="size-3" /> : <XCircle className="size-3" />}
      {status}
    </span>
  );
}

function ExamStatusBadge({ status }: { status: string }) {
  const isDraft = status === "DRAFT";
  return (
    <span
      className={`px-2.5 py-1 rounded-full text-xs font-semibold inline-flex items-center gap-1 ${
        isDraft
          ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500"
          : "bg-green-500/20 text-green-400 border border-green-500"
      }`}
    >
      {isDraft ? <FileEdit className="size-3" /> : <CheckCircle className="size-3" />}
      {status}
    </span>
  );
}

// ── Questions Modal ──────────────────────────────────────────

function QuestionsModal({
  questions,
  onClose,
}: {
  questions: ExamQuestion[];
  onClose: () => void;
}) {
  const LABELS = ["", "A", "B", "C", "D"];
  return (
    <Modal title={`Questions (${questions.length})`} onClose={onClose}>
      <div className="max-h-[60vh] overflow-y-auto space-y-4 pr-1">
        {questions.map((q, i) => (
          <div key={q.id} className="p-4 bg-gray-800/40 rounded-lg border border-gray-700">
            <div className="flex items-start justify-between gap-2 mb-3">
              <p className="text-white text-sm font-medium">
                <span className="text-gray-500">Q{i + 1}.</span> {q.question}
              </p>
              <span className="text-gray-500 text-xs shrink-0">{q.marks} marks</span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {[
                { key: 1, label: "A", val: q.optionA },
                { key: 2, label: "B", val: q.optionB },
                { key: 3, label: "C", val: q.optionC },
                { key: 4, label: "D", val: q.optionD },
              ].filter(o => o.val).map((o) => (
                <div
                  key={o.key}
                  className={`px-3 py-2 rounded text-xs ${
                    q.correctAnswer === o.key
                      ? "bg-green-500/20 border border-green-500 text-green-400"
                      : "bg-gray-800 text-gray-400"
                  }`}
                >
                  <span className="font-bold mr-1">{o.label}.</span> {o.val}
                </div>
              ))}
            </div>
            {q.description && (
              <p className="text-gray-500 text-xs mt-2 italic">{q.description}</p>
            )}
          </div>
        ))}
      </div>
    </Modal>
  );
}

// ── Pass Rate Modal ──────────────────────────────────────────

function PassRateModal({
  results,
  onClose,
}: {
  results: ExamStudentResult[];
  onClose: () => void;
}) {
  const passed = results.filter((r) => r.status === "Passed");
  const failed = results.filter((r) => r.status === "Failed");

  return (
    <Modal title="Pass / Fail Breakdown" onClose={onClose}>
      <div className="max-h-[60vh] overflow-y-auto space-y-6 pr-1">
        {/* Passed */}
        <div>
          <h3 className="text-green-400 font-semibold text-sm mb-3 flex items-center gap-2">
            <CheckCircle className="size-4" />
            Passed ({passed.length})
          </h3>
          {passed.length === 0 ? (
            <p className="text-gray-500 text-sm">No students passed.</p>
          ) : (
            <div className="space-y-2">
              {passed.map((r) => (
                <div key={r.student.id} className="flex items-center justify-between p-3 bg-green-500/10 border border-green-500/20 rounded-lg">
                  <div className="min-w-0">
                    <p className="text-white text-sm font-medium truncate">{r.student.fullName}</p>
                    <p className="text-gray-400 text-xs truncate">{r.student.email}</p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <span className="text-white text-sm font-semibold">{r.percentage}%</span>
                    <GradeBadge grade={r.grade} />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Failed */}
        <div>
          <h3 className="text-red-400 font-semibold text-sm mb-3 flex items-center gap-2">
            <XCircle className="size-4" />
            Failed ({failed.length})
          </h3>
          {failed.length === 0 ? (
            <p className="text-gray-500 text-sm">No students failed.</p>
          ) : (
            <div className="space-y-2">
              {failed.map((r) => (
                <div key={r.student.id} className="flex items-center justify-between p-3 bg-red-500/10 border border-red-500/20 rounded-lg">
                  <div className="min-w-0">
                    <p className="text-white text-sm font-medium truncate">{r.student.fullName}</p>
                    <p className="text-gray-400 text-xs truncate">{r.student.email}</p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <span className="text-white text-sm font-semibold">{r.percentage}%</span>
                    <GradeBadge grade={r.grade} />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

// ── Top Scores Modal ─────────────────────────────────────────

function TopScoresModal({
  results,
  onClose,
}: {
  results: ExamStudentResult[];
  onClose: () => void;
}) {
  const top10 = [...results].sort((a, b) => b.percentage - a.percentage).slice(0, 10);

  return (
    <Modal title="Top 10 Highest Scores" onClose={onClose}>
      <div className="max-h-[60vh] overflow-y-auto space-y-2 pr-1">
        {top10.length === 0 ? (
          <p className="text-gray-500 text-sm text-center py-8">No submissions yet.</p>
        ) : (
          top10.map((r, i) => (
            <div
              key={r.student.id}
              className="flex items-center gap-3 p-3 bg-gray-800/40 rounded-lg border border-gray-700"
            >
              <span className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${
                i === 0 ? "bg-yellow-500/20 text-yellow-400" :
                i === 1 ? "bg-gray-300/20 text-gray-300" :
                i === 2 ? "bg-orange-500/20 text-orange-400" :
                "bg-gray-800 text-gray-500"
              }`}>
                {i === 0 ? <Trophy className="size-4" /> : i + 1}
              </span>
              <div className="flex-1 min-w-0">
                <p className="text-white text-sm font-medium truncate">{r.student.fullName}</p>
                <p className="text-gray-400 text-xs truncate">{r.student.email}</p>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <span className="text-white text-sm font-bold">{r.percentage}%</span>
                <GradeBadge grade={r.grade} />
              </div>
            </div>
          ))
        )}
      </div>
    </Modal>
  );
}

// ── Mobile Result Card ───────────────────────────────────────

function ResultCard({
  result,
  onClick,
}: {
  result: ExamStudentResult;
  onClick: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className="p-4 bg-gray-800/40 rounded-lg border border-gray-700 space-y-3 cursor-pointer hover:border-gray-600 transition-colors"
    >
      <div className="flex items-start justify-between">
        <div className="min-w-0">
          <p className="text-white font-medium truncate">{result.student.fullName}</p>
          <p className="text-gray-400 text-sm truncate">{result.student.email}</p>
        </div>
        <GradeBadge grade={result.grade} />
      </div>
      <div className="flex items-center justify-between flex-wrap gap-2">
        <span className="text-white text-sm font-semibold">
          {result.score}/{result.totalMarks} ({result.percentage}%)
        </span>
        <StatusBadge status={result.status} />
      </div>
      <p className="text-gray-500 text-xs">
        {new Date(result.submittedAt).toLocaleDateString()}
      </p>
    </div>
  );
}

// ── Main Page ────────────────────────────────────────────────

type ModalType = "questions" | "passRate" | "topScores" | null;

export default function ExamResultsPage() {
  const router = useRouter();
  const params = useParams();
  const examId = params.examId as string;

  const { data, isLoading, isError } = useExamResults(examId);
  const { data: examDetail } = useExamDetail(examId);
  const [activeModal, setActiveModal] = useState<ModalType>(null);

  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">
        <XCircle className="size-12 text-red-400" />
        <p className="text-red-400 text-lg">Failed to load exam results</p>
        <Button onClick={() => router.push("/admin/course")} variant="secondary">
          Back to Course
        </Button>
      </div>
    );
  }

  const { exam, summary, results } = data;
  const questions = examDetail?.questions ?? [];
  const passRate = summary.attempted > 0 ? Math.round((summary.passed / summary.attempted) * 100) : 0;
  const attemptRate = summary.totalStudents > 0 ? Math.round((summary.attempted / summary.totalStudents) * 100) : 0;

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Back + Header */}
      <div>
        <button
          onClick={() => router.push("/admin/course")}
          className="flex items-center gap-1.5 text-gray-400 hover:text-white text-sm mb-4 transition-colors"
        >
          <ArrowLeft className="size-4" />
          Back to Course
        </button>
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-white">{exam.title}</h1>
            <div className="flex items-center gap-3 mt-2 flex-wrap">
              <span className="text-gray-400 text-sm flex items-center gap-1.5">
                <BookOpen className="size-4" />
                {exam.course}
              </span>
              {exam.cohort && (
                <span className="text-cyan-400 text-sm flex items-center gap-1.5">
                  <Layers className="size-4" />
                  {exam.cohort.batch} ({exam.cohort.month} {exam.cohort.year})
                </span>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500">
              {exam.type}
            </span>
            <ExamStatusBadge status={exam.status} />
            <Button
              size="sm"
              variant="secondary"
              onClick={() => router.push(`/admin/course/exam/${examId}`)}
            >
              <FileEdit className="size-4 mr-1.5" />
              Edit Exam
            </Button>
          </div>
        </div>
      </div>

      {/* Exam Info Cards — Questions is clickable */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
        <div
          onClick={() => questions.length > 0 && setActiveModal("questions")}
          className={`p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl ${
            questions.length > 0 ? "cursor-pointer hover:border-gray-600 transition-colors" : ""
          }`}
        >
          <div className="flex items-center gap-2 mb-2">
            <ClipboardList className="size-4 text-gray-400" />
            <span className="text-gray-400 text-xs">Questions</span>
          </div>
          <p className="text-white text-xl font-bold">{exam.totalQuestions}</p>
          {questions.length > 0 && (
            <p className="text-blue-400 text-xs mt-1">Click to view</p>
          )}
        </div>
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
          <div className="flex items-center gap-2 mb-2">
            <Award className="size-4 text-gray-400" />
            <span className="text-gray-400 text-xs">Total Marks</span>
          </div>
          <p className="text-white text-xl font-bold">{exam.totalMarks}</p>
        </div>
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
          <div className="flex items-center gap-2 mb-2">
            <Clock className="size-4 text-gray-400" />
            <span className="text-gray-400 text-xs">Duration</span>
          </div>
          <p className="text-white text-xl font-bold">{exam.duration} min</p>
        </div>
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
          <div className="flex items-center gap-2 mb-2">
            <Calendar className="size-4 text-gray-400" />
            <span className="text-gray-400 text-xs">Created</span>
          </div>
          <p className="text-white text-xl font-bold">{exam.createdAt}</p>
        </div>
      </div>

      {/* Performance Summary — Pass Rate + Highest Score clickable */}
      <div>
        <h2 className="text-lg font-semibold text-white mb-3 flex items-center gap-2">
          <BarChart3 className="size-5 text-gray-400" />
          Performance Summary
        </h2>
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
          <StatCard
            icon={Users}
            gradient="from-blue-500 to-blue-600"
            label="Total Students"
            value={summary.totalStudents}
            subtext={`${summary.attempted} attempted (${attemptRate}%)`}
          />
          <StatCard
            icon={Target}
            gradient="from-green-500 to-green-600"
            label="Pass Rate"
            value={`${passRate}%`}
            subtext={`${summary.passed} passed, ${summary.failed} failed`}
            onClick={results.length > 0 ? () => setActiveModal("passRate") : undefined}
          />
          <StatCard
            icon={TrendingUp}
            gradient="from-purple-500 to-purple-600"
            label="Highest Score"
            value={summary.attempted > 0 ? `${summary.highestScore}%` : "—"}
            onClick={results.length > 0 ? () => setActiveModal("topScores") : undefined}
          />
          <StatCard
            icon={TrendingDown}
            gradient="from-yellow-500 to-yellow-600"
            label="Average Score"
            value={summary.attempted > 0 ? `${summary.averageScore}%` : "—"}
            subtext={summary.attempted > 0 ? `Lowest: ${summary.lowestScore}%` : undefined}
          />
        </div>
      </div>

      {/* Student Results */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2">
            <Users className="size-5 text-gray-400" />
            Student Results
          </h2>
          {results.length > 0 && (
            <span className="text-gray-500 text-sm">
              {results.length} {results.length === 1 ? "submission" : "submissions"}
            </span>
          )}
        </div>

        {results.length === 0 ? (
          <div className="p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl text-center">
            <Users className="size-12 text-gray-600 mx-auto mb-4" />
            <p className="text-gray-400 text-lg">No submissions yet</p>
            <p className="text-gray-500 text-sm mt-1">
              Students haven&apos;t attempted this exam yet.
            </p>
          </div>
        ) : (
          <>
            {/* Mobile: card layout */}
            <div className="space-y-3 md:hidden">
              {results.map((r) => (
                <ResultCard
                  key={r.student.id}
                  result={r}
                  onClick={() => router.push(`/admin/course/exam/${examId}/results/${r.student.id}`)}
                />
              ))}
            </div>

            {/* Desktop: table layout */}
            <div className="hidden md:block bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl overflow-hidden">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="border-gray-800 hover:bg-gray-800/50">
                      <TableHead className="text-gray-300 font-bold">#</TableHead>
                      <TableHead className="text-gray-300 font-bold">Student</TableHead>
                      <TableHead className="text-gray-300 font-bold">Email</TableHead>
                      <TableHead className="text-gray-300 font-bold">Score</TableHead>
                      <TableHead className="text-gray-300 font-bold">Percentage</TableHead>
                      <TableHead className="text-gray-300 font-bold">Grade</TableHead>
                      <TableHead className="text-gray-300 font-bold">Status</TableHead>
                      <TableHead className="text-gray-300 font-bold">Submitted</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {results.map((r, i) => (
                      <TableRow
                        key={r.student.id}
                        className="border-gray-800 hover:bg-gray-800/50 transition-colors cursor-pointer"
                        onClick={() => router.push(`/admin/course/exam/${examId}/results/${r.student.id}`)}
                      >
                        <TableCell className="text-gray-500 font-medium">{i + 1}</TableCell>
                        <TableCell className="text-white font-medium">{r.student.fullName}</TableCell>
                        <TableCell className="text-gray-400">{r.student.email}</TableCell>
                        <TableCell className="text-white font-semibold">
                          {r.score}/{r.totalMarks}
                        </TableCell>
                        <TableCell className="text-white font-semibold">{r.percentage}%</TableCell>
                        <TableCell>
                          <GradeBadge grade={r.grade} />
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={r.status} />
                        </TableCell>
                        <TableCell className="text-gray-400 text-sm">
                          {new Date(r.submittedAt).toLocaleDateString()}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Modals */}
      {activeModal === "questions" && questions.length > 0 && (
        <QuestionsModal questions={questions} onClose={() => setActiveModal(null)} />
      )}
      {activeModal === "passRate" && (
        <PassRateModal results={results} onClose={() => setActiveModal(null)} />
      )}
      {activeModal === "topScores" && (
        <TopScoresModal results={results} onClose={() => setActiveModal(null)} />
      )}
    </div>
  );
}
