"use client";

import { useState } from "react";
import {
  FileQuestion,
  Users,
  CheckCircle,
  TrendingUp,
  Plus,
  Calendar,
  ArrowRight,
  Layers,
  ChevronDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { AddStudentModal } from "@/components/dashboard/add-student-modal";
import { useStudentList } from "@/lib/api/hooks/useStudent";
import { useAdminCourse, useAdminAnalytics } from "@/lib/api/hooks/useAdmin";
import type { LucideIcon } from "lucide-react";

// ── Stat card ────────────────────────────────────────────────

function StatCard({
  icon: Icon, gradient, label, value,
}: {
  icon: LucideIcon; gradient: string; label: string; value: string | number;
}) {
  return (
    <div className="p-4 sm:p-5 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
      <div className="mb-3">
        <div className={`inline-flex p-2.5 bg-gradient-to-br ${gradient} rounded-xl`}>
          <Icon className="size-5 text-white" />
        </div>
      </div>
      <p className="text-xs sm:text-sm text-gray-400 mb-0.5">{label}</p>
      <p className="text-2xl sm:text-3xl font-bold text-white">{value}</p>
    </div>
  );
}

// ── Main ─────────────────────────────────────────────────────

type ViewType = "dashboard" | "students";

export default function AdminDashboard() {
  const [activeView, setActiveView] = useState<ViewType>("dashboard");
  const [showAddStudent, setShowAddStudent] = useState(false);
  const [addCohortId, setAddCohortId] = useState("");

  // Real API data
  const { data: studentData, isLoading: studentsLoading } = useStudentList();
  const { data: courseData } = useAdminCourse();
  const { data: analyticsData } = useAdminAnalytics();
  const students = studentData?.students ?? [];
  const courseName = studentData?.course ?? "";

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

  const previewStudents = students.slice(0, 5);

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

  function openAddStudent() {
    if (!addCohortId && cohorts.length > 0) {
      setAddCohortId(cohorts[0].id);
    }
    setShowAddStudent(true);
  }

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-white">
            Dashboard Overview
          </h1>
          <p className="text-sm sm:text-base text-gray-400 mt-1">
            Monitor and manage your examination portal
          </p>
        </div>
        <div className="flex gap-2">
          {([
            { key: "dashboard", label: "Dashboard" },
            { key: "students", label: "Students" },
          ] as const).map((tab) => (
            <Button
              key={tab.key}
              onClick={() => setActiveView(tab.key)}
              className={`${
                activeView === tab.key
                  ? "bg-green-600 hover:bg-green-700"
                  : "bg-gray-800 hover:bg-gray-700"
              } text-white`}
              size="md"
            >
              {tab.label}
            </Button>
          ))}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-5">
        <StatCard icon={FileQuestion} gradient="from-blue-500 to-blue-600" label="Total Questions" value={analyticsData?.overview.totalQuestions ?? 0} />
        <StatCard icon={Users} gradient="from-purple-500 to-purple-600" label="Total Students" value={analyticsData?.overview.totalStudents ?? students.length} />
        <StatCard icon={CheckCircle} gradient="from-green-500 to-green-600" label="Pass Rate" value={`${analyticsData?.overview.passRate ?? 0}%`} />
        <StatCard icon={TrendingUp} gradient="from-yellow-500 to-yellow-600" label="Avg. Score" value={`${analyticsData?.overview.averageScore ?? 0}%`} />
      </div>

      {/* ── Dashboard View ────────────────────────────────── */}
      {activeView === "dashboard" && (
        <div className="p-5 sm:p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
          <div className="flex items-center justify-between mb-5">
            <h2 className="text-lg sm:text-xl font-bold text-white">Students</h2>
            {students.length > 5 && (
              <button
                onClick={() => setActiveView("students")}
                className="text-blue-400 hover:text-blue-300 text-sm font-medium flex items-center gap-1 transition-colors"
              >
                View All
                <ArrowRight className="size-4" />
              </button>
            )}
          </div>

          {studentsLoading && (
            <div className="flex justify-center py-8">
              <Spinner className="size-6 text-blue-500" />
            </div>
          )}

          {!studentsLoading && previewStudents.length === 0 && (
            <div className="text-center py-10">
              <Users className="size-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400">No students yet</p>
              <p className="text-gray-500 text-sm mt-1">Add your first student to get started.</p>
            </div>
          )}

          {!studentsLoading && previewStudents.length > 0 && (
            <div className="space-y-3">
              {previewStudents.map((s) => (
                <div
                  key={s.id}
                  className="flex flex-col sm:flex-row sm:items-center justify-between p-3 rounded-lg bg-gray-800/40 hover:bg-gray-800/60 transition-colors gap-2"
                >
                  <div className="min-w-0">
                    <p className="text-white text-sm font-medium truncate">{s.fullName}</p>
                    <p className="text-gray-500 text-xs truncate">{s.email}</p>
                  </div>
                  <div className="flex items-center gap-3 shrink-0">
                    {s.cohort && (
                      <span className="px-2 py-0.5 rounded-full text-xs bg-cyan-500/20 text-cyan-400 border border-cyan-500">
                        {s.cohort.batch}
                      </span>
                    )}
                    <div className="flex items-center gap-2 text-gray-400 text-xs">
                      <Calendar className="size-3.5" />
                      <span>{s.dateAdded}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ── Students View ─────────────────────────────────── */}
      {activeView === "students" && (
        <div className="space-y-5">
          {/* Header with course name + add button */}
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
              {courseName && (
                <p className="text-gray-400 text-sm">
                  Course: <span className="text-white font-medium">{courseName}</span>
                </p>
              )}
              {cohorts.length > 0 && (
                <p className="text-gray-500 text-xs mt-0.5 flex items-center gap-1">
                  <Layers className="size-3" />
                  {cohorts.length} {cohorts.length === 1 ? "cohort" : "cohorts"}
                </p>
              )}
            </div>
            {cohorts.length > 0 && (
              <div className="flex items-center gap-2">
                {cohorts.length > 1 && (
                  <div className="relative shrink-0">
                    <select
                      value={addCohortId || cohorts[0]?.id || ""}
                      onChange={(e) => setAddCohortId(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"
                    >
                      {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>
                )}
                <Button
                  onClick={openAddStudent}
                  className="bg-green-600 hover:bg-green-700 text-white font-semibold shrink-0"
                >
                  <Plus className="size-5 mr-2" />
                  Add Student
                </Button>
              </div>
            )}
          </div>

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

          {!studentsLoading && students.length === 0 && (
            <div className="text-center py-16">
              <Users className="size-12 text-gray-600 mx-auto mb-4" />
              <p className="text-gray-400 text-lg">No students yet</p>
              <p className="text-gray-500 text-sm mt-1">Add your first student to get started.</p>
            </div>
          )}

          {!studentsLoading && students.length > 0 && (
            <div className="space-y-3">
              {students.map((s) => (
                <div
                  key={s.id}
                  className="p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl flex flex-col sm:flex-row sm:items-center justify-between gap-3"
                >
                  <div className="min-w-0">
                    <p className="text-white font-medium">{s.fullName}</p>
                    <p className="text-gray-400 text-sm truncate">{s.email}</p>
                  </div>
                  <div className="flex items-center gap-3 text-sm shrink-0">
                    {s.cohort && (
                      <span className="px-2 py-0.5 rounded-full text-xs bg-cyan-500/20 text-cyan-400 border border-cyan-500">
                        {s.cohort.batch} ({s.cohort.month} {s.cohort.year})
                      </span>
                    )}
                    <div className="flex items-center gap-2 text-gray-400">
                      <Calendar className="size-4 shrink-0" />
                      <span>{s.dateAdded}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Add Student Modal */}
      {showAddStudent && selectedCohort && (
        <AddStudentModal
          cohortId={addCohortId || selectedCohort.id}
          cohortLabel={cohortLabel}
          onClose={() => setShowAddStudent(false)}
          onSuccess={() => {}}
        />
      )}
    </div>
  );
}
