"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  BookOpen,
  Users,
  Clock,
  ClipboardList,
  Plus,
  CheckCircle,
  FileEdit,
  Eye,
  Trash2,
  Layers,
  ChevronDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { CreateExamModal } from "@/components/dashboard/create-exam-modal";
import { useAdminCourse } from "@/lib/api/hooks/useAdmin";
import { useStudentList } from "@/lib/api/hooks/useStudent";
import { useExamList, useDeleteExam } from "@/lib/api/hooks/useExam";
import type { ExamListItem } from "@/types/api";

function StatusBadge({ 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>
  );
}

function TypeBadge({ type }: { type: string }) {
  return (
    <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500">
      {type}
    </span>
  );
}

function CohortBadge({ cohort }: { cohort: { batch: string; month: string; year: number } }) {
  return (
    <span className="px-2 py-0.5 rounded-full text-xs bg-cyan-500/20 text-cyan-400 border border-cyan-500">
      {cohort.batch}
    </span>
  );
}

function ExamCard({
  exam,
  onView,
  onDelete,
}: {
  exam: ExamListItem;
  onView: () => void;
  onDelete: () => void;
}) {
  return (
    <div className="p-4 sm:p-5 bg-gray-800/40 rounded-lg border border-gray-700 hover:border-gray-600 transition-colors">
      <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3 mb-3">
        <div className="min-w-0">
          <h4 className="text-white font-semibold truncate">{exam.title}</h4>
          <p className="text-gray-500 text-xs mt-0.5">{exam.createdAt}</p>
        </div>
        <div className="flex items-center gap-2 shrink-0 flex-wrap">
          <CohortBadge cohort={exam.cohort} />
          <TypeBadge type={exam.type} />
          <StatusBadge status={exam.status} />
        </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} {exam.totalQuestions === 1 ? "question" : "questions"}
        </span>
        <span className="flex items-center gap-1.5">
          <Clock className="size-4" />
          {exam.duration} min
        </span>
      </div>
      <div className="flex gap-2">
        <Button
          size="sm"
          className="bg-blue-600 hover:bg-blue-700 text-white"
          onClick={onView}
        >
          <Eye className="size-4 mr-1.5" />
          {exam.status === "DRAFT" ? "Edit" : "View"}
        </Button>
        {exam.status === "DRAFT" && (
          <Button size="sm" variant="danger" onClick={onDelete}>
            <Trash2 className="size-4" />
          </Button>
        )}
      </div>
    </div>
  );
}

export default function CoursePage() {
  const router = useRouter();
  const [selectedCohortId, setSelectedCohortId] = useState<string>("");
  const [showCreateExam, setShowCreateExam] = useState(false);

  const { data: courseData, isLoading: coursesLoading } = useAdminCourse();
  const { data: studentData, isLoading: studentsLoading } = useStudentList();
  const { data: examData, isLoading: examsLoading } = useExamList(selectedCohortId || undefined);
  const deleteExam = useDeleteExam();

  const courseName = studentData?.course ?? courseData?.course?.name ?? "";
  const studentCount = studentData?.students?.length ?? 0;
  const exams = examData?.exams ?? [];

  // Get cohorts from admin's course endpoint
  const cohorts = courseData?.course?.cohorts ?? [];

  const isLoading = studentsLoading || examsLoading || coursesLoading;

  const selectedCohort = cohorts.find((c) => c.id === selectedCohortId) ?? cohorts[0];
  const cohortLabel = selectedCohort
    ? `${selectedCohort.batch} (${selectedCohort.month} ${selectedCohort.year})`
    : "All Cohorts";

  function handleDeleteExam(exam: ExamListItem) {
    if (!confirm(`Are you sure you want to delete "${exam.title}"?`)) return;
    deleteExam.mutate(exam.id);
  }

  function handleExamCreated(examId: string) {
    router.push(`/admin/course/exam/${examId}`);
  }

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

  if (!courseName) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-center">
        <BookOpen className="size-16 text-gray-600 mb-4" />
        <h1 className="text-2xl font-bold text-white mb-2">No Course Assigned</h1>
        <p className="text-gray-400">
          You haven&apos;t been assigned to a course yet. Contact the super admin.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-white">
          My Course
        </h1>
        <p className="text-sm sm:text-base text-gray-400 mt-1">
          Manage your course cohorts and exams
        </p>
      </div>

      {/* Course Detail Card */}
      <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 items-start gap-4 mb-6">
          <div className="p-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shrink-0">
            <BookOpen className="size-7 text-white" />
          </div>
          <div>
            <h2 className="text-xl sm:text-2xl font-bold text-white">{courseName}</h2>
            <div className="flex items-center gap-4 mt-1 flex-wrap">
              <div className="flex items-center gap-2">
                <Layers className="size-4 text-gray-400" />
                <span className="text-gray-400 text-sm">
                  {cohorts.length} {cohorts.length === 1 ? "cohort" : "cohorts"}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Users className="size-4 text-gray-400" />
                <span className="text-gray-400 text-sm">
                  {studentCount} students total
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Cohort Selector */}
        {cohorts.length > 0 && (
          <div className="mb-6">
            <label className="text-sm text-gray-400 mb-2 block">Filter by Cohort</label>
            <div className="relative inline-block">
              <select
                value={selectedCohortId}
                onChange={(e) => setSelectedCohortId(e.target.value)}
                className="appearance-none pl-4 pr-10 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">All Cohorts</option>
                {cohorts.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.batch} ({c.month} {c.year})
                  </option>
                ))}
              </select>
              <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 size-4 text-gray-400 pointer-events-none" />
            </div>
          </div>
        )}

        <div className="h-px bg-gray-800 my-6" />

        {/* Exams Section */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
              <ClipboardList className="size-5 text-gray-400" />
              Exams
              {selectedCohort && selectedCohortId && (
                <span className="text-sm text-gray-500 font-normal">
                  — {selectedCohort.batch}
                </span>
              )}
            </h3>
            {cohorts.length > 0 && (
              <Button
                onClick={() => {
                  if (!selectedCohortId) setSelectedCohortId(cohorts[0].id);
                  setShowCreateExam(true);
                }}
                className="bg-green-600 hover:bg-green-700 text-white"
                size="sm"
              >
                <Plus className="size-4 mr-1.5" />
                Add Exam
              </Button>
            )}
          </div>

          {exams.length === 0 ? (
            <div className="p-6 bg-gray-800/30 rounded-lg border border-dashed border-gray-700 text-center">
              <ClipboardList className="size-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400 mb-1">No exams yet</p>
              <p className="text-gray-500 text-sm">
                Create an exam to start testing your students.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {exams.map((exam) => (
                <ExamCard
                  key={exam.id}
                  exam={exam}
                  onView={() => router.push(
                    exam.status === "DRAFT"
                      ? `/admin/course/exam/${exam.id}`
                      : `/admin/course/exam/${exam.id}/results`
                  )}
                  onDelete={() => handleDeleteExam(exam)}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Modals */}
      {showCreateExam && selectedCohort && (
        <CreateExamModal
          cohortId={selectedCohortId || selectedCohort.id}
          cohortLabel={cohortLabel}
          onClose={() => setShowCreateExam(false)}
          onSuccess={handleExamCreated}
        />
      )}
    </div>
  );
}
