import prisma from "@/lib/prisma";
import { getSessionUser } from "@/lib/auth";
import { PageHeader } from "@/components/layout/PageHeader";
import { StatCard } from "@/components/dashboard/StatCard";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatDateID, getDeadlineStatus } from "@/lib/utils";
import Link from "next/link";
import {
  Layers,
  Users,
  ClipboardList,
  Clock,
  PlusCircle,
  FileCheck,
  CheckCircle2,
  Calendar,
  ArrowRight,
  BookOpen,
} from "lucide-react";

export default async function TeacherDashboardPage() {
  const user = await getSessionUser();
  if (!user || !user.teacherId) return null;

  // Find teacher info and their classes/subjects
  const teacher = await prisma.teacher.findUnique({
    where: { id: user.teacherId },
    include: {
      teacherSubjects: {
        include: {
          subject: true,
          class: {
            include: {
              members: true,
            },
          },
          schedules: true,
          assignments: {
            include: {
              submissions: {
                include: { student: true },
              },
            },
          },
          materials: {
            orderBy: { createdAt: "desc" },
            take: 4,
          },
        },
      },
    },
  });

  if (!teacher) return null;

  // Aggregate stats
  const assignedClassesCount = teacher.teacherSubjects.length;
  let totalStudents = 0;
  teacher.teacherSubjects.forEach((ts) => {
    totalStudents += ts.class.members.length;
  });

  // Calculate pending grading submissions
  const pendingSubmissions: any[] = [];
  let activeAssignmentsCount = 0;
  const now = new Date();

  teacher.teacherSubjects.forEach((ts) => {
    ts.assignments.forEach((assign) => {
      if (new Date(assign.dueDate) > now) {
        activeAssignmentsCount++;
      }
      assign.submissions.forEach((sub) => {
        if (sub.status === "SUBMITTED" || sub.score === null) {
          pendingSubmissions.push({
            ...sub,
            assignmentTitle: assign.title,
            subjectName: ts.subject.name,
            className: ts.class.name,
          });
        }
      });
    });
  });

  // Schedules (Today or all upcoming)
  const currentDayOfWeek = new Date().getDay() === 0 ? 7 : new Date().getDay(); // 1=Senin..7=Minggu
  const allSchedules: any[] = [];
  teacher.teacherSubjects.forEach((ts) => {
    ts.schedules.forEach((sch) => {
      allSchedules.push({
        ...sch,
        subjectName: ts.subject.name,
        className: ts.class.name,
      });
    });
  });

  // Sort schedules by time
  allSchedules.sort((a, b) => a.startTime.localeCompare(b.startTime));
  const todaySchedules = allSchedules.filter((s) => s.dayOfWeek === currentDayOfWeek);

  return (
    <div className="space-y-6">
      {/* Header */}
      <PageHeader
        title={`Dashboard Guru: ${teacher.fullName}`}
        description="Pantau jadwal mengajar, modul materi, serta koreksi tugas & kuis siswa."
      >
        <div className="flex flex-wrap items-center gap-2">
          <Link href="/teacher/materials">
            <Button size="sm" variant="outline" className="text-xs">
              <PlusCircle className="mr-1.5 h-3.5 w-3.5" />
              Buat Materi
            </Button>
          </Link>
          <Link href="/teacher/assignments">
            <Button size="sm" variant="outline" className="text-xs">
              <PlusCircle className="mr-1.5 h-3.5 w-3.5" />
              Buat Tugas
            </Button>
          </Link>
          <Link href="/teacher/quizzes">
            <Button size="sm" variant="outline" className="text-xs">
              <FileCheck className="mr-1.5 h-3.5 w-3.5" />
              Buat Kuis CBT
            </Button>
          </Link>
          <Link href="/teacher/attendance">
            <Button size="sm" className="text-xs">
              <CheckCircle2 className="mr-1.5 h-3.5 w-3.5" />
              Input Presensi
            </Button>
          </Link>
        </div>
      </PageHeader>

      {/* METRIC STATS */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Kelas Diampu"
          value={assignedClassesCount}
          subtitle="Rombongan belajar"
          iconName="subject"
          colorScheme="blue"
        />
        <StatCard
          title="Total Siswa"
          value={totalStudents}
          subtitle="Di seluruh kelas diajar"
          iconName="users"
          colorScheme="emerald"
        />
        <StatCard
          title="Tugas Berjalan"
          value={activeAssignmentsCount}
          subtitle="Sedang aktif"
          iconName="assignment"
          colorScheme="purple"
        />
        <StatCard
          title="Menunggu Penilaian"
          value={pendingSubmissions.length}
          subtitle="Tugas perlu dikoreksi"
          iconName="clock"
          colorScheme={pendingSubmissions.length > 0 ? "rose" : "emerald"}
        />
      </div>

      {/* 2-COLUMN LAYOUT: Today Schedule & Submissions to Grade */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Today's Schedule Card */}
        <Card className="lg:col-span-1">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle>Jadwal Mengajar</CardTitle>
            <Link
              href="/teacher/schedules"
              className="text-xs font-semibold text-blue-600 hover:underline"
            >
              Lihat Semua &rarr;
            </Link>
          </CardHeader>
          <CardContent className="space-y-3 pt-2">
            {todaySchedules.length > 0 ? (
              todaySchedules.map((sch) => (
                <div
                  key={sch.id}
                  className="p-3.5 rounded-xl border border-blue-100 bg-blue-50/50 space-y-1.5"
                >
                  <div className="flex items-center justify-between">
                    <Badge variant="primary">{sch.className}</Badge>
                    <span className="text-xs font-bold font-mono text-blue-700">
                      {sch.startTime} - {sch.endTime}
                    </span>
                  </div>
                  <h4 className="text-sm font-bold text-slate-800">
                    {sch.subjectName}
                  </h4>
                  <p className="text-xs text-slate-500 flex items-center gap-1">
                    <Clock className="h-3 w-3" />
                    Ruang: {sch.room || "Ruang Kelas"}
                  </p>
                </div>
              ))
            ) : (
              <div className="text-center py-6 text-slate-400 space-y-2">
                <Calendar className="h-8 w-8 mx-auto text-slate-300" />
                <p className="text-xs">Tidak ada jam mengajar hari ini.</p>
                <div className="pt-2 text-left space-y-2">
                  <p className="text-[11px] font-bold text-slate-600">
                    Jadwal Mengajar Pekan Ini:
                  </p>
                  {allSchedules.slice(0, 3).map((s) => (
                    <div
                      key={s.id}
                      className="p-2 rounded-lg bg-slate-50 border border-slate-100 flex justify-between text-xs"
                    >
                      <span className="font-semibold text-slate-700">
                        {s.subjectName} ({s.className})
                      </span>
                      <span className="text-slate-500 font-mono">
                        {s.startTime}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Submissions Waiting for Grading */}
        <Card className="lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <div>
              <CardTitle>Tugas Siswa Menunggu Penilaian</CardTitle>
              <p className="text-xs text-slate-500 mt-1">
                Koreksi dan berikan umpan balik (feedback) pada jawaban siswa
              </p>
            </div>
            {pendingSubmissions.length > 0 && (
              <Badge variant="warning">{pendingSubmissions.length} Tugas Baru</Badge>
            )}
          </CardHeader>
          <CardContent className="pt-2">
            {pendingSubmissions.length === 0 ? (
              <div className="p-8 text-center text-slate-400 text-xs">
                <CheckCircle2 className="h-8 w-8 text-emerald-500 mx-auto mb-2" />
                Semua tugas yang dikumpulkan siswa telah dinilai!
              </div>
            ) : (
              <div className="space-y-2.5">
                {pendingSubmissions.slice(0, 5).map((sub) => (
                  <div
                    key={sub.id}
                    className="p-3.5 rounded-xl border border-slate-200/80 bg-white hover:border-blue-400 flex flex-col sm:flex-row sm:items-center justify-between gap-3 transition-all"
                  >
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <Badge variant="secondary">{sub.className}</Badge>
                        <span className="text-xs font-bold text-slate-800">
                          {sub.student.fullName}
                        </span>
                        <span className="text-[11px] text-slate-400 font-mono">
                          (NIS: {sub.student.nis})
                        </span>
                      </div>
                      <p className="text-xs text-slate-600 font-medium">
                        {sub.assignmentTitle}
                      </p>
                      <p className="text-[10px] text-slate-400 mt-0.5">
                        Dikumpulkan: {formatDateID(sub.submittedAt, true)}
                      </p>
                    </div>

                    <Link
                      href={`/teacher/assignments/${sub.assignmentId}/submissions`}
                    >
                      <Button size="sm" variant="outline" className="text-xs font-bold">
                        Beri Nilai &rarr;
                      </Button>
                    </Link>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Kelas Diajar Overview */}
      <div className="space-y-3">
        <h3 className="text-sm font-bold text-slate-800">
          Daftar Rombel & Mata Pelajaran Diampu
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {teacher.teacherSubjects.map((ts) => (
            <div
              key={ts.id}
              className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3"
            >
              <div className="flex items-center justify-between">
                <Badge variant="primary">{ts.class.name}</Badge>
                <span className="text-xs text-slate-500 font-medium">
                  {ts.class.members.length} Siswa
                </span>
              </div>

              <div>
                <h4 className="text-base font-bold text-slate-900">
                  {ts.subject.name}
                </h4>
                <p className="text-xs text-slate-500 mt-0.5">
                  Kode: {ts.subject.code}
                </p>
              </div>

              <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-xs">
                <Link
                  href={`/teacher/materials?classId=${ts.classId}`}
                  className="font-semibold text-blue-600 hover:underline"
                >
                  {ts.materials.length} Materi Modul
                </Link>
                <Link
                  href={`/teacher/gradebook?tsId=${ts.id}`}
                  className="font-semibold text-emerald-600 hover:underline"
                >
                  Buku Nilai &rarr;
                </Link>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
