"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  BookOpen,
  ClipboardList,
  Clock,
  GraduationCap,
  Layers,
  CheckCircle,
  Play,
} from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import { useStudentExams, useStudentAllResults } from "@/lib/api/hooks/useStudentAuth";
import { getStoredUser } from "@/lib/api/client";
import type { StudentProfile, StudentExamItem } from "@/types/api";

function ExamCard({
  exam,
  submitted,
  resultGrade,
  onStart,
  onViewResult,
}: {
  exam: StudentExamItem;
  submitted: boolean;
  resultGrade?: string;
  onStart: () => void;
  onViewResult: () => void;
}) {
  return (
    <div className="p-4 sm:p-5 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl hover:border-gray-700 transition-all duration-200">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="min-w-0">
          <h3 className="text-white font-semibold truncate">{exam.title}</h3>
          <p className="text-gray-500 text-xs mt-0.5">
            {exam.course}
            {exam.cohort && (
              <span className="text-cyan-400"> — {exam.cohort.batch}</span>
            )}
          </p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          {submitted && resultGrade && (
            <span className="px-2.5 py-1 rounded-full text-xs font-bold bg-green-500/20 text-green-400 border border-green-500">
              {resultGrade}
            </span>
          )}
          <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500 shrink-0">
            {exam.type}
          </span>
        </div>
      </div>
      <div className="flex flex-wrap gap-4 text-sm text-gray-400 mb-4">
        <span className="flex items-center gap-1.5">
          <ClipboardList className="size-4" />
          {exam.totalQuestions} questions
        </span>
        <span className="flex items-center gap-1.5">
          <Clock className="size-4" />
          {exam.duration} min
        </span>
      </div>
      {submitted ? (
        <button
          onClick={onViewResult}
          className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2"
        >
          <CheckCircle className="size-4" />
          View Result
        </button>
      ) : (
        <button
          onClick={onStart}
          className="w-full py-2.5 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2"
        >
          <Play className="size-4" />
          Start Exam
        </button>
      )}
    </div>
  );
}

export default function StudentDashboard() {
  const router = useRouter();
  const { data, isLoading, isError } = useStudentExams();
  const { data: resultsData } = useStudentAllResults();
  const [student, setStudent] = useState<StudentProfile | null>(null);

  useEffect(() => {
    const stored = getStoredUser();
    if (stored) setStudent(stored);
  }, []);

  const exams = data?.exams ?? [];
  const results = resultsData?.results ?? [];
  const enrollments = student?.enrollments ?? [];

  // Build a map of examId -> result for quick lookup
  const resultMap = new Map(results.map((r) => [r.exam.id, r]));

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Welcome */}
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold text-white">
          Welcome back, {student?.fullName?.split(" ")[0] ?? "Student"}
        </h1>
        <p className="text-sm sm:text-base text-gray-400 mt-1">
          Here are your enrollments and available exams
        </p>
      </div>

      {/* Enrollments */}
      {enrollments.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-white mb-3 flex items-center gap-2">
            <BookOpen className="size-5 text-gray-400" />
            My Enrollments
          </h2>
          <div className="flex flex-wrap gap-3">
            {enrollments.map((e) => (
              <div
                key={`${e.course.id}-${e.cohort.id}`}
                className="px-4 py-3 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl flex items-center gap-3"
              >
                <div className="p-2 bg-green-500/20 rounded-lg">
                  <GraduationCap className="size-4 text-green-400" />
                </div>
                <div>
                  <span className="text-white font-medium text-sm">{e.course.name}</span>
                  <p className="text-gray-500 text-xs flex items-center gap-1">
                    <Layers className="size-3" />
                    {e.cohort.batch} ({e.cohort.month} {e.cohort.year})
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Available Exams */}
      <div>
        <h2 className="text-lg font-semibold text-white mb-3 flex items-center gap-2">
          <ClipboardList className="size-5 text-gray-400" />
          Available Exams
        </h2>

        {isLoading && (
          <div className="flex justify-center py-12">
            <Spinner className="size-8 text-green-500" />
          </div>
        )}

        {!isLoading && isError && (
          <div className="text-center py-16 bg-gradient-to-br from-gray-900 to-black border border-red-500/30 rounded-xl">
            <ClipboardList className="size-12 text-red-400 mx-auto mb-4" />
            <p className="text-red-400 text-lg">Failed to load exams</p>
            <p className="text-gray-500 text-sm mt-1">Please try refreshing the page.</p>
          </div>
        )}

        {!isLoading && !isError && exams.length === 0 && (
          <div className="text-center py-16 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
            <ClipboardList className="size-12 text-gray-600 mx-auto mb-4" />
            <p className="text-gray-400 text-lg">No exams available</p>
            <p className="text-gray-500 text-sm mt-1">
              Check back later or contact your admin.
            </p>
          </div>
        )}

        {!isLoading && !isError && exams.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {exams.map((exam) => {
              const result = resultMap.get(exam.id);
              return (
                <ExamCard
                  key={exam.id}
                  exam={exam}
                  submitted={!!result}
                  resultGrade={result?.grade}
                  onStart={() => router.push(`/student/exam/${exam.id}`)}
                  onViewResult={() => router.push(`/student/exam/${exam.id}/result`)}
                />
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
