"use client";

import { useRouter, useParams } from "next/navigation";
import {
  Trophy,
  CheckCircle,
  XCircle,
  MinusCircle,
  ArrowLeft,
  ClipboardList,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { useExamResult } from "@/lib/api/hooks/useStudentAuth";
import type { ReviewQuestion } from "@/types/api";

const OPTION_LABELS = ["", "A", "B", "C", "D"];

function getAnswerText(q: ReviewQuestion, answer: number): string {
  if (answer === 0) return "Skipped";
  if (answer === 1) return q.optionA;
  if (answer === 2) return q.optionB;
  if (answer === 3) return q.optionC;
  if (answer === 4) return q.optionD;
  return "Unknown";
}

const GRADE_COLORS: Record<string, string> = {
  A: "from-green-500 to-green-600 border-green-500",
  B: "from-blue-500 to-blue-600 border-blue-500",
  C: "from-yellow-500 to-yellow-600 border-yellow-500",
  D: "from-orange-500 to-orange-600 border-orange-500",
  F: "from-red-500 to-red-600 border-red-500",
};

const GRADING_SCALE = [
  { grade: "A", range: "90-100%", color: "border-green-500 text-green-400" },
  { grade: "B", range: "80-89%", color: "border-blue-500 text-blue-400" },
  { grade: "C", range: "70-79%", color: "border-yellow-500 text-yellow-400" },
  { grade: "D", range: "60-69%", color: "border-orange-500 text-orange-400" },
  { grade: "F", range: "Below 60%", color: "border-red-500 text-red-400" },
];

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

  const { data, isLoading, isError } = useExamResult(examId);

  if (isLoading) {
    return (
      <div className="flex justify-center py-20">
        <Spinner className="size-8 text-green-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">Result not found</p>
        <Button onClick={() => router.push("/student/dashboard")} variant="secondary">
          Back to Dashboard
        </Button>
      </div>
    );
  }

  const { exam, result, review } = data;
  const passed = result.status === "Passed";
  const incorrectCount = result.totalQuestions - result.correctAnswers;
  const unansweredCount = review.filter((q) => q.studentAnswer === 0).length;
  const incorrectAnswered = incorrectCount - unansweredCount;

  const gradeColor = GRADE_COLORS[result.grade] ?? GRADE_COLORS.F;

  const performanceMessage = result.percentage >= 90
    ? "Outstanding Performance!"
    : result.percentage >= 80
    ? "Great Performance!"
    : result.percentage >= 70
    ? "Good Performance!"
    : result.percentage >= 50
    ? "Decent Performance"
    : "Keep Working Hard!";

  return (
    <div className="max-w-2xl mx-auto py-6 sm:py-10 space-y-6">
      {/* Header */}
      <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl text-center">
        <div className="w-16 h-16 mx-auto mb-3 bg-yellow-500/20 rounded-full flex items-center justify-center">
          <Trophy className="size-8 text-yellow-400" />
        </div>
        <h1 className="text-2xl sm:text-3xl font-bold text-white">Exam Results</h1>
        <p className="text-gray-400 text-sm mt-1">{performanceMessage}</p>
      </div>

      {/* Grade Card */}
      <div className={`p-6 bg-gradient-to-br from-gray-900 to-black border rounded-xl text-center ${gradeColor.split(" ").pop()}`}>
        <p className="text-gray-500 text-xs uppercase tracking-wider mb-2">Your Grade</p>
        <p className="text-6xl sm:text-7xl font-black text-white mb-2">{result.grade}</p>
        <p className="text-white text-lg font-semibold">{result.percentage.toFixed(1)}%</p>
      </div>

      {/* Stats: Correct / Incorrect / Unanswered */}
      <div className="grid grid-cols-3 gap-3 sm:gap-4">
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-green-500/30 rounded-xl text-center">
          <CheckCircle className="size-6 text-green-500 mx-auto mb-2" />
          <p className="text-gray-500 text-xs mb-1">Correct Answers</p>
          <p className="text-white text-2xl font-bold">{result.correctAnswers}</p>
        </div>
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-red-500/30 rounded-xl text-center">
          <XCircle className="size-6 text-red-500 mx-auto mb-2" />
          <p className="text-gray-500 text-xs mb-1">Incorrect Answers</p>
          <p className="text-red-400 text-2xl font-bold">{incorrectAnswered}</p>
        </div>
        <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-700 rounded-xl text-center">
          <MinusCircle className="size-6 text-gray-500 mx-auto mb-2" />
          <p className="text-gray-500 text-xs mb-1">Unanswered</p>
          <p className="text-white text-2xl font-bold">{unansweredCount}</p>
        </div>
      </div>

      {/* Score Breakdown */}
      <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
        <h2 className="text-white font-bold mb-4 flex items-center gap-2">
          <TrendingUpIcon />
          Score Breakdown
        </h2>
        <div className="grid grid-cols-2 gap-3">
          <div className="p-3 bg-gray-800/50 border border-gray-700 rounded-lg flex items-center justify-between">
            <span className="text-gray-400 text-sm">Total Score:</span>
            <span className="text-white font-bold">{result.score} / {result.totalMarks}</span>
          </div>
          <div className="p-3 bg-gray-800/50 border border-gray-700 rounded-lg flex items-center justify-between">
            <span className="text-gray-400 text-sm">Percentage:</span>
            <span className="text-white font-bold">{result.percentage.toFixed(2)}%</span>
          </div>
          <div className="p-3 bg-gray-800/50 border border-gray-700 rounded-lg flex items-center justify-between">
            <span className="text-gray-400 text-sm">Grade:</span>
            <span className="text-white font-bold">{result.grade}</span>
          </div>
          <div className="p-3 bg-gray-800/50 border border-gray-700 rounded-lg flex items-center justify-between">
            <span className="text-gray-400 text-sm">Status:</span>
            <span className={`font-bold flex items-center gap-1 ${passed ? "text-green-400" : "text-red-400"}`}>
              {result.status}
              {passed ? <CheckCircle className="size-4" /> : <XCircle className="size-4" />}
            </span>
          </div>
        </div>
      </div>

      {/* Detailed Review */}
      {review.length > 0 && (
        <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
          <h2 className="text-white font-bold mb-4 flex items-center gap-2">
            <ClipboardList className="size-5" />
            Detailed Review
          </h2>
          <div className="space-y-3 max-h-[400px] overflow-y-auto pr-1">
            {review.map((q) => {
              const answerLabel = q.studentAnswer > 0 ? OPTION_LABELS[q.studentAnswer] : null;
              const answerText = getAnswerText(q, q.studentAnswer);
              return (
                <div
                  key={q.id}
                  className={`p-4 rounded-xl border-l-4 bg-gray-800/30 ${
                    q.isCorrect
                      ? "border-l-green-500"
                      : q.studentAnswer === 0
                      ? "border-l-gray-600"
                      : "border-l-red-500"
                  }`}
                >
                  <div className="flex items-start gap-2">
                    {q.isCorrect ? (
                      <CheckCircle className="size-5 text-green-500 shrink-0 mt-0.5" />
                    ) : (
                      <XCircle className="size-5 text-red-500 shrink-0 mt-0.5" />
                    )}
                    <div className="min-w-0">
                      <p className="text-white text-sm font-medium">
                        Q{q.number}. {q.question}
                      </p>
                      <p className="text-gray-400 text-xs mt-1">
                        Your answer:{" "}
                        <span className={q.isCorrect ? "text-green-400" : q.studentAnswer === 0 ? "text-gray-500" : "text-red-400"}>
                          {answerLabel ? `${answerLabel}. ` : ""}{answerText}
                        </span>
                      </p>
                      {!q.isCorrect && (
                        <p className="text-gray-500 text-xs mt-0.5">
                          Correct answer:{" "}
                          <span className="text-green-400">
                            {OPTION_LABELS[q.correctAnswer]}. {getAnswerText(q, q.correctAnswer)}
                          </span>
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Grading Scale */}
      <div className="p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
        <h2 className="text-white font-bold mb-4">Grading Scale</h2>
        <div className="grid grid-cols-5 gap-2 sm:gap-3">
          {GRADING_SCALE.map((g) => (
            <div
              key={g.grade}
              className={`p-3 border rounded-xl text-center ${g.color}`}
            >
              <p className="text-2xl font-black">{g.grade}</p>
              <p className="text-[10px] sm:text-xs opacity-70">{g.range}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Back button */}
      <div className="text-center">
        <Button
          className="bg-green-600 hover:bg-green-700 text-white"
          onClick={() => router.push("/student/dashboard")}
        >
          <ClipboardList className="size-4 mr-2" />
          Back to Dashboard
        </Button>
      </div>
    </div>
  );
}

// Simple inline icon to avoid another import
function TrendingUpIcon() {
  return (
    <svg className="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" />
      <polyline points="17 6 23 6 23 12" />
    </svg>
  );
}
