"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useRouter, useParams } from "next/navigation";
import {
  Clock,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  CheckCircle,
  ClipboardList,
  Award,
  Target,
  TrendingUp,
  Send,
  Lightbulb,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { useStartExam, useSubmitExam } from "@/lib/api/hooks/useStudentAuth";
import { ApiRequestError } from "@/lib/api";
import type { StudentExamQuestion, SubmitExamResult } from "@/types/api";

type ExamState = "loading" | "ready" | "in-progress" | "submitting" | "submitted" | "error";

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

  const startExam = useStartExam();
  const submitExam = useSubmitExam();

  const [state, setState] = useState<ExamState>("loading");
  const [error, setError] = useState("");
  const [examTitle, setExamTitle] = useState("");
  const [duration, setDuration] = useState(0);
  const [totalMarks, setTotalMarks] = useState(0);
  const [questions, setQuestions] = useState<StudentExamQuestion[]>([]);
  const [answers, setAnswers] = useState<Record<string, number>>({});
  const [currentQ, setCurrentQ] = useState(0);
  const [timeLeft, setTimeLeft] = useState(0);
  const [result, setResult] = useState<SubmitExamResult | null>(null);
  const [showConfirm, setShowConfirm] = useState(false);
  const submittedRef = useRef(false);

  // Start exam on mount
  useEffect(() => {
    startExam.mutate(examId, {
      onSuccess: (data) => {
        setExamTitle(data.exam.title);
        setDuration(data.exam.duration);
        setTotalMarks(data.exam.totalMarks);
        setQuestions(data.questions);
        setTimeLeft(data.exam.duration * 60);
        setState("ready");
      },
      onError: (err) => {
        if (err instanceof ApiRequestError) setError(err.message);
        else setError("Failed to load exam.");
        setState("error");
      },
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [examId]);

  // Timer
  useEffect(() => {
    if (state !== "in-progress" || timeLeft <= 0) return;
    const timer = setInterval(() => {
      setTimeLeft((t) => {
        if (t <= 1) { clearInterval(timer); return 0; }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [state, timeLeft]);

  // Auto-submit
  const handleSubmit = useCallback(() => {
    if (submittedRef.current) return;
    submittedRef.current = true;
    setState("submitting");
    submitExam.mutate(
      { examId, data: { answers } },
      {
        onSuccess: (res) => { setResult(res.result); setState("submitted"); },
        onError: (err) => {
          submittedRef.current = false;
          if (err instanceof ApiRequestError) setError(err.message);
          else setError("Failed to submit exam.");
          setState("error");
        },
      }
    );
  }, [examId, answers, submitExam]);

  useEffect(() => {
    if (state === "in-progress" && timeLeft === 0) handleSubmit();
  }, [state, timeLeft, handleSubmit]);

  function selectAnswer(questionId: string, option: number) {
    setAnswers((prev) => ({
      ...prev,
      [questionId]: prev[questionId] === option ? 0 : option,
    }));
  }

  const answeredCount = Object.values(answers).filter((v) => v > 0).length;
  const minutes = Math.floor(timeLeft / 60);
  const seconds = timeLeft % 60;
  const totalSeconds = duration * 60;
  const progressPercent = totalSeconds > 0 ? ((totalSeconds - timeLeft) / totalSeconds) * 100 : 0;
  const isLowTime = timeLeft <= 60;

  // ── Loading ────────────────────────────────────────────────
  if (state === "loading") {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4">
        <Spinner className="size-8 text-green-500" />
        <p className="text-gray-400">Loading exam...</p>
      </div>
    );
  }

  // ── Error ──────────────────────────────────────────────────
  if (state === "error") {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4 text-center">
        <AlertTriangle className="size-12 text-red-400" />
        <p className="text-red-400 text-lg">{error}</p>
        <Button onClick={() => router.push("/student/dashboard")} variant="secondary">
          Back to Dashboard
        </Button>
      </div>
    );
  }

  // ── Ready (pre-start) ─────────────────────────────────────
  if (state === "ready") {
    return (
      <div className="max-w-4xl mx-auto py-6 sm:py-10 space-y-6">
        {/* Stat Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
          {[
            { icon: ClipboardList, label: "Total Questions", value: String(questions.length) },
            { icon: Clock, label: "Time Limit", value: `${duration} min` },
            { icon: Award, label: "Total Marks", value: String(totalMarks) },
            { icon: Target, label: "Pass Percentage", value: "45%" },
          ].map((stat) => (
            <div key={stat.label} className="p-4 sm:p-5 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gray-800 rounded-lg">
                  <stat.icon className="size-5 text-gray-400" />
                </div>
                <div>
                  <p className="text-gray-500 text-xs">{stat.label}</p>
                  <p className="text-white text-xl sm:text-2xl font-bold">{stat.value}</p>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Main content: Exam Details + Instructions */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
          {/* Exam Details */}
          <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
            <div className="flex flex-col items-center text-center mb-6">
              <div className="w-20 h-20 bg-gray-800 rounded-2xl flex items-center justify-center mb-4">
                <ClipboardList className="size-10 text-gray-400" />
              </div>
              <h1 className="text-xl sm:text-2xl font-bold text-white">{examTitle}</h1>
            </div>

            <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-xl space-y-4">
              <h3 className="text-white font-semibold text-sm">Exam Details</h3>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gray-700/50 rounded-lg">
                  <ClipboardList className="size-4 text-gray-400" />
                </div>
                <div>
                  <p className="text-white text-sm font-medium">Total Questions</p>
                  <p className="text-gray-500 text-xs">{questions.length} Multiple Choice Questions</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gray-700/50 rounded-lg">
                  <Clock className="size-4 text-gray-400" />
                </div>
                <div>
                  <p className="text-white text-sm font-medium">Duration</p>
                  <p className="text-gray-500 text-xs">{duration} minutes (Auto-submit enabled)</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gray-700/50 rounded-lg">
                  <Award className="size-4 text-gray-400" />
                </div>
                <div>
                  <p className="text-white text-sm font-medium">Grading System</p>
                  <p className="text-gray-500 text-xs">A/B/C/D/F based on percentage</p>
                </div>
              </div>
            </div>

            <Button
              className="w-full mt-6 bg-green-600 hover:bg-green-700 text-white text-base py-6"
              onClick={() => setState("in-progress")}
            >
              <ClipboardList className="size-5 mr-2" />
              Start Examination
            </Button>
          </div>

          {/* Instructions */}
          <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
            <h2 className="text-lg font-bold text-white mb-5 flex items-center gap-2">
              <TrendingUp className="size-5" />
              Instructions
            </h2>
            <ul className="space-y-3">
              {[
                "Read each question carefully before selecting your answer",
                "You can navigate between questions using the question navigator",
                "Timer will be displayed at the top - manage your time wisely",
                "Exam will auto-submit when time expires",
                "Each question has only one correct answer",
                "You can change your answers before final submission",
                "Results will be displayed immediately after submission",
              ].map((instruction) => (
                <li key={instruction} className="flex items-start gap-3 text-gray-300 text-sm">
                  <span className="mt-1.5 w-1.5 h-1.5 bg-green-500 rounded-full shrink-0" />
                  {instruction}
                </li>
              ))}
            </ul>
            <div className="mt-6 p-4 bg-blue-500/10 border border-blue-500/30 rounded-lg">
              <p className="text-blue-400 text-sm flex items-start gap-2">
                <Lightbulb className="size-4 shrink-0 mt-0.5" />
                Tip: Make sure you have a stable internet connection before starting the exam
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Submitted ──────────────────────────────────────────────
  if (state === "submitted" && result) {
    const passed = result.status === "Passed";
    return (
      <div className="max-w-lg mx-auto py-12">
        <div className="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-4 rounded-full flex items-center justify-center ${
            passed ? "bg-green-500/20" : "bg-red-500/20"
          }`}>
            <CheckCircle className={`size-8 ${passed ? "text-green-400" : "text-red-400"}`} />
          </div>
          <h1 className="text-2xl font-bold text-white mb-1">Exam Submitted!</h1>
          <p className="text-gray-400 mb-6">{examTitle}</p>

          <div className="grid grid-cols-2 gap-4 mb-6">
            <div className="p-4 bg-gray-800/50 rounded-lg">
              <p className="text-gray-500 text-xs mb-1">Score</p>
              <p className="text-white text-xl font-bold">{result.score}/{result.totalMarks}</p>
            </div>
            <div className="p-4 bg-gray-800/50 rounded-lg">
              <p className="text-gray-500 text-xs mb-1">Percentage</p>
              <p className="text-white text-xl font-bold">{result.percentage}%</p>
            </div>
            <div className="p-4 bg-gray-800/50 rounded-lg">
              <p className="text-gray-500 text-xs mb-1">Grade</p>
              <p className="text-white text-xl font-bold">{result.grade}</p>
            </div>
            <div className="p-4 bg-gray-800/50 rounded-lg">
              <p className="text-gray-500 text-xs mb-1">Status</p>
              <p className={`text-xl font-bold ${passed ? "text-green-400" : "text-red-400"}`}>
                {result.status}
              </p>
            </div>
          </div>

          <p className="text-gray-500 text-sm mb-6">
            {result.correctAnswers} of {result.totalQuestions} questions correct
          </p>

          <div className="flex gap-3 justify-center">
            <Button
              variant="secondary"
              onClick={() => router.push(`/student/exam/${examId}/result`)}
            >
              View Detailed Result
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700 text-white"
              onClick={() => router.push("/student/dashboard")}
            >
              Back to Dashboard
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // ── In Progress ────────────────────────────────────────────
  const q = questions[currentQ];

  return (
    <div className="flex flex-col min-h-[calc(100vh-4rem)]">
      {/* Fixed Header */}
      <div className="sticky top-0 z-10 bg-gray-900 border-b border-gray-800 p-3 sm:p-4">
        <div className="max-w-6xl mx-auto flex items-center gap-4">
          <div className="shrink-0">
            <p className="text-gray-500 text-xs">Time Remaining</p>
            <p className={`text-2xl font-bold font-mono ${isLowTime ? "text-red-400 animate-pulse" : "text-white"}`}>
              {String(minutes).padStart(2, "0")}:{String(seconds).padStart(2, "0")}
            </p>
          </div>
          {/* Progress bar */}
          <div className="flex-1 hidden sm:block">
            <p className="text-gray-500 text-xs mb-1">Progress</p>
            <div className="h-2.5 bg-gray-800 rounded-full overflow-hidden">
              <div
                className="h-full bg-gradient-to-r from-blue-500 to-blue-600 rounded-full transition-all duration-1000"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>
          <div className="text-right shrink-0">
            <p className="text-gray-500 text-xs">Answered</p>
            <p className="text-white font-semibold">{answeredCount} / {questions.length}</p>
          </div>
          <Button
            className="bg-green-600 hover:bg-green-700 text-white shrink-0"
            size="sm"
            onClick={() => setShowConfirm(true)}
          >
            <Send className="size-4 mr-1.5" />
            Submit Exam
          </Button>
        </div>
      </div>

      {/* Body: Navigator + Question */}
      <div className="flex-1 max-w-6xl mx-auto w-full flex flex-col lg:flex-row gap-4 sm:gap-6 p-4 sm:p-6">
        {/* Question Navigator Sidebar */}
        <div className="lg:w-56 shrink-0">
          <div className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
            <h3 className="text-white font-semibold text-sm mb-3">Question Navigator</h3>
            <div className="grid grid-cols-6 lg:grid-cols-3 gap-2">
              {questions.map((question, i) => {
                const isAnswered = answers[question.id] && answers[question.id] > 0;
                const isCurrent = i === currentQ;
                return (
                  <button
                    key={question.id}
                    onClick={() => setCurrentQ(i)}
                    className={`w-full aspect-square rounded-lg text-sm font-semibold transition-all flex items-center justify-center ${
                      isCurrent
                        ? "bg-white text-black"
                        : isAnswered
                        ? "bg-green-600 text-white"
                        : "bg-gray-800 text-gray-400 border border-gray-700"
                    }`}
                  >
                    {i + 1}
                  </button>
                );
              })}
            </div>
            {/* Legend */}
            <div className="mt-4 space-y-2">
              <div className="flex items-center gap-2 text-xs text-gray-400">
                <span className="w-4 h-4 rounded bg-white shrink-0" />
                Current
              </div>
              <div className="flex items-center gap-2 text-xs text-gray-400">
                <span className="w-4 h-4 rounded bg-green-600 shrink-0" />
                Answered
              </div>
              <div className="flex items-center gap-2 text-xs text-gray-400">
                <span className="w-4 h-4 rounded bg-gray-800 border border-gray-700 shrink-0" />
                Not Answered
              </div>
            </div>
          </div>
        </div>

        {/* Question Content */}
        {q && (
          <div className="flex-1">
            <div className="p-6 sm:p-8 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
              {/* Question header */}
              <div className="flex items-center justify-between mb-2">
                <p className="text-gray-500 text-sm">
                  Question {currentQ + 1} of {questions.length} • {q.marks} marks
                </p>
                {answers[q.id] && answers[q.id] > 0 && (
                  <CheckCircle className="size-6 text-green-500" />
                )}
              </div>

              <h2 className="text-white text-lg sm:text-xl font-semibold mb-6">{q.question}</h2>

              {/* Options */}
              <div className="space-y-3">
                {[
                  { key: 1, label: "A", value: q.optionA },
                  { key: 2, label: "B", value: q.optionB },
                  ...(q.type === "MULTIPLE_CHOICE"
                    ? [
                        { key: 3, label: "C", value: q.optionC },
                        { key: 4, label: "D", value: q.optionD },
                      ]
                    : []),
                ].filter(opt => opt.value).map((opt) => {
                  const selected = answers[q.id] === opt.key;
                  return (
                    <button
                      key={opt.key}
                      onClick={() => selectAnswer(q.id, opt.key)}
                      className={`w-full text-left p-4 rounded-xl border transition-all flex items-center gap-3 ${
                        selected
                          ? "bg-green-600/15 border-green-500"
                          : "bg-gray-800/50 border-gray-700 hover:border-gray-600"
                      }`}
                    >
                      <span className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 ${
                        selected ? "border-green-500 bg-green-500" : "border-gray-600"
                      }`}>
                        {selected && <span className="w-2 h-2 bg-white rounded-full" />}
                      </span>
                      <span className="text-gray-500 font-semibold text-sm mr-1">{opt.label}.</span>
                      <span className={selected ? "text-white" : "text-gray-300"}>{opt.value}</span>
                    </button>
                  );
                })}
              </div>

              {/* Navigation */}
              <div className="flex items-center justify-between mt-8">
                <Button
                  variant="secondary"
                  disabled={currentQ === 0}
                  onClick={() => setCurrentQ((c) => c - 1)}
                >
                  <ChevronLeft className="size-4 mr-1" />
                  Previous
                </Button>
                <p className="text-gray-500 text-sm hidden sm:block">
                  Question {currentQ + 1} of {questions.length}
                </p>
                {currentQ < questions.length - 1 ? (
                  <Button
                    className="bg-blue-600 hover:bg-blue-700 text-white"
                    onClick={() => setCurrentQ((c) => c + 1)}
                  >
                    Next
                    <ChevronRight className="size-4 ml-1" />
                  </Button>
                ) : (
                  <Button
                    className="bg-green-600 hover:bg-green-700 text-white"
                    onClick={() => setShowConfirm(true)}
                  >
                    <Send className="size-4 mr-2" />
                    Submit
                  </Button>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Submit confirmation modal */}
      {showConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
          <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 max-w-sm w-full">
            <h3 className="text-white font-bold text-lg mb-2">Submit Exam?</h3>
            <p className="text-gray-400 text-sm mb-1">
              You have answered <span className="text-white font-semibold">{answeredCount}</span> of{" "}
              <span className="text-white font-semibold">{questions.length}</span> questions.
            </p>
            {answeredCount < questions.length && (
              <p className="text-yellow-400 text-sm mb-4 flex items-center gap-1.5">
                <AlertTriangle className="size-4 shrink-0" />
                {questions.length - answeredCount} unanswered questions will score 0.
              </p>
            )}
            <div className="flex gap-3 justify-end mt-4">
              <Button variant="secondary" onClick={() => setShowConfirm(false)}>
                Review
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700 text-white"
                disabled={state === "submitting"}
                onClick={() => { setShowConfirm(false); handleSubmit(); }}
              >
                {state === "submitting" ? "Submitting..." : "Confirm Submit"}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
