import prisma from "@/lib/prisma";
import { getSessionUser } from "@/lib/auth";
import { PageHeader } from "@/components/layout/PageHeader";
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 {
  BookOpen,
  ClipboardList,
  CheckCircle2,
  Clock,
  Calendar,
  Award,
  AlertTriangle,
  ArrowRight,
  Sparkles,
  FileCheck,
} from "lucide-react";

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

  const student = await prisma.student.findUnique({
    where: { id: user.studentId },
    include: {
      classMembers: {
        include: {
          class: {
            include: {
              teacherSubjects: {
                include: {
                  subject: true,
                  teacher: true,
                  materials: {
                    where: { isPublished: true },
                    orderBy: { createdAt: "desc" },
                    take: 3,
                  },
                  assignments: {
                    where: { isPublished: true },
                    include: {
                      submissions: {
                        where: { studentId: user.studentId },
                      },
                    },
                    orderBy: { dueDate: "asc" },
                  },
                  schedules: true,
                  quizzes: {
                    where: { isPublished: true },
                    include: {
                      attempts: {
                        where: { studentId: user.studentId },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
      submissions: {
        where: { score: { not: null } },
        include: { assignment: { include: { teacherSubject: { include: { subject: true } } } } },
        orderBy: { gradedAt: "desc" },
        take: 3,
      },
      attendances: {
        take: 10,
        orderBy: { createdAt: "desc" },
      },
    },
  });

  if (!student || student.classMembers.length === 0) {
    return (
      <div className="p-8 text-center text-slate-500">
        Akun siswa Anda belum dimasukkan ke rombel kelas aktif oleh administrator.
      </div>
    );
  }

  const currentClass = student.classMembers[0].class;
  const teacherSubjects = currentClass.teacherSubjects;

  // Flatten pending assignments
  const pendingAssignments: any[] = [];
  const submittedAssignments: any[] = [];

  teacherSubjects.forEach((ts) => {
    ts.assignments.forEach((assign) => {
      const mySubmission = assign.submissions[0];
      const item = {
        ...assign,
        subjectName: ts.subject.name,
        mySubmission,
      };
      if (!mySubmission) {
        pendingAssignments.push(item);
      } else {
        submittedAssignments.push(item);
      }
    });
  });

  // Today's schedule
  const currentDayOfWeek = new Date().getDay() === 0 ? 7 : new Date().getDay();
  const allSchedules: any[] = [];
  teacherSubjects.forEach((ts) => {
    ts.schedules.forEach((sch) => {
      allSchedules.push({
        ...sch,
        subjectName: ts.subject.name,
        teacherName: ts.teacher.fullName,
      });
    });
  });
  allSchedules.sort((a, b) => a.startTime.localeCompare(b.startTime));
  const todaySchedules = allSchedules.filter((s) => s.dayOfWeek === currentDayOfWeek);

  // Latest materials
  const latestMaterials: any[] = [];
  teacherSubjects.forEach((ts) => {
    ts.materials.forEach((m) => {
      latestMaterials.push({
        ...m,
        subjectName: ts.subject.name,
      });
    });
  });
  latestMaterials.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

  // Active quizzes
  const activeQuizzes: any[] = [];
  teacherSubjects.forEach((ts) => {
    ts.quizzes.forEach((q) => {
      const completedAttempt = q.attempts.find((att) => att.isCompleted);
      activeQuizzes.push({
        ...q,
        subjectName: ts.subject.name,
        completedAttempt,
      });
    });
  });

  return (
    <div className="space-y-6">
      {/* Welcome Banner */}
      <div className="relative overflow-hidden rounded-3xl bg-gradient-to-r from-blue-900 via-indigo-900 to-slate-900 p-6 md:p-8 text-white shadow-lg">
        <div className="relative z-10 max-w-2xl space-y-3">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 text-xs font-semibold text-blue-200 border border-white/10">
            <Sparkles className="h-3.5 w-3.5 text-amber-400" />
            Kelas {currentClass.name} • SMAN 3 OKU
          </div>
          <h1 className="text-2xl md:text-3xl font-black tracking-tight">
            Halo, {student.fullName}!
          </h1>
          <p className="text-xs md:text-sm text-blue-100/90 leading-relaxed">
            Selamat datang di portal pembelajaran digital. Periksa jadwal belajar hari ini, kerjakan tugas sebelum deadline, dan pantau pengumuman terbaru.
          </p>
        </div>
      </div>

      {/* 2-COLUMN LAYOUT: Left (Tasks & Schedule) - Right (Materials & Grades) */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* LEFT 2 COLS */}
        <div className="lg:col-span-2 space-y-6">
          {/* PENDING ASSIGNMENTS WITH COLOR-CODED DEADLINE */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <div>
                <CardTitle>Tugas Belum Selesai</CardTitle>
                <p className="text-xs text-slate-500 mt-0.5">
                  Indikator warna batas akhir pengumpulan
                </p>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-[10px] flex items-center gap-1 font-semibold text-emerald-600">
                  <span className="h-2 w-2 rounded-full bg-emerald-500" /> Aman
                </span>
                <span className="text-[10px] flex items-center gap-1 font-semibold text-amber-600">
                  <span className="h-2 w-2 rounded-full bg-amber-500" /> Mendekati
                </span>
                <span className="text-[10px] flex items-center gap-1 font-semibold text-rose-600">
                  <span className="h-2 w-2 rounded-full bg-rose-500" /> Kritis/Telat
                </span>
              </div>
            </CardHeader>
            <CardContent className="pt-2">
              {pendingAssignments.length === 0 ? (
                <div className="p-8 text-center text-xs text-slate-400">
                  <CheckCircle2 className="h-8 w-8 text-emerald-500 mx-auto mb-2" />
                  Semua tugas Anda telah dikumpulkan. Kerja bagus!
                </div>
              ) : (
                <div className="space-y-3">
                  {pendingAssignments.map((assign) => {
                    const deadlineInfo = getDeadlineStatus(assign.dueDate);
                    return (
                      <div
                        key={assign.id}
                        className="p-4 rounded-xl border border-slate-200 hover:border-blue-400 bg-white shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-3 transition-all"
                      >
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <Badge variant="primary">{assign.subjectName}</Badge>
                            <span
                              className={`text-[11px] font-bold px-2 py-0.5 rounded-full border ${deadlineInfo.badgeClass}`}
                            >
                              {deadlineInfo.label}
                            </span>
                          </div>
                          <h4 className="text-sm font-bold text-slate-800">
                            {assign.title}
                          </h4>
                          <p className="text-xs text-slate-500 flex items-center gap-1">
                            <Clock className="h-3 w-3" />
                            Batas Waktu: {formatDateID(assign.dueDate, true)}
                          </p>
                        </div>

                        <Link href={`/student/assignments/${assign.id}`}>
                          <Button size="sm" className="font-bold text-xs shrink-0 w-full sm:w-auto">
                            Kerjakan Tugas
                            <ArrowRight className="ml-1.5 h-3.5 w-3.5" />
                          </Button>
                        </Link>
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>

          {/* ACTIVE CBT QUIZZES / EXAMS */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <div>
                <CardTitle>Kuis & Ujian Online (CBT)</CardTitle>
                <p className="text-xs text-slate-500 mt-0.5">
                  Asesmen formatif & sumatif berbasis komputer
                </p>
              </div>
              <Link
                href="/student/quizzes"
                className="text-xs font-bold text-blue-600 hover:underline"
              >
                Lihat Semua &rarr;
              </Link>
            </CardHeader>
            <CardContent className="space-y-3 pt-2">
              {activeQuizzes.length === 0 ? (
                <p className="text-xs text-slate-400 py-4 text-center">
                  Tidak ada kuis atau ujian yang aktif saat ini.
                </p>
              ) : (
                activeQuizzes.map((quiz) => (
                  <div
                    key={quiz.id}
                    className="p-3.5 rounded-xl border border-slate-200 bg-white flex flex-col sm:flex-row sm:items-center justify-between gap-3"
                  >
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <Badge variant="secondary">{quiz.subjectName}</Badge>
                        <span className="text-[11px] text-slate-500">
                          {quiz.durationMinutes} Menit
                        </span>
                      </div>
                      <h4 className="text-sm font-bold text-slate-800">
                        {quiz.title}
                      </h4>
                    </div>

                    {quiz.completedAttempt ? (
                      <div className="flex items-center gap-2">
                        <Badge variant="success">
                          Skor: {quiz.completedAttempt.totalScore}
                        </Badge>
                        <span className="text-xs text-emerald-600 font-semibold">
                          Selesai
                        </span>
                      </div>
                    ) : (
                      <Link href={`/student/quizzes/${quiz.id}/take`}>
                        <Button size="sm" variant="gold" className="text-xs font-bold">
                          Mulai Ujian &rarr;
                        </Button>
                      </Link>
                    )}
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </div>

        {/* RIGHT COLUMN */}
        <div className="space-y-6">
          {/* Today's Schedule */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle>Jadwal Pelajaran Hari Ini</CardTitle>
              <p className="text-xs text-slate-500">
                Pukul 07.30 - 15.00 WIB
              </p>
            </CardHeader>
            <CardContent className="space-y-2.5 pt-2">
              {todaySchedules.length > 0 ? (
                todaySchedules.map((sch) => (
                  <div
                    key={sch.id}
                    className="p-3 rounded-xl border border-blue-100 bg-blue-50/50 space-y-1"
                  >
                    <div className="flex items-center justify-between text-xs font-mono font-bold text-blue-700">
                      <span>{sch.startTime} - {sch.endTime}</span>
                      <span className="font-sans font-medium text-[11px] text-slate-500">
                        {sch.room || "Ruang Kelas"}
                      </span>
                    </div>
                    <h5 className="text-xs font-bold text-slate-800">
                      {sch.subjectName}
                    </h5>
                    <p className="text-[11px] text-slate-500">
                      Guru: {sch.teacherName}
                    </p>
                  </div>
                ))
              ) : (
                <div className="text-center py-6 text-slate-400 space-y-2">
                  <Calendar className="h-6 w-6 mx-auto text-slate-300" />
                  <p className="text-xs">Tidak ada jam pelajaran aktif hari ini.</p>
                  <Link
                    href="/student/schedules"
                    className="text-xs font-bold text-blue-600 hover:underline block pt-1"
                  >
                    Buka Jadwal Mingguan &rarr;
                  </Link>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Recent Released Grades */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle>Nilai Terbaru</CardTitle>
              <Link
                href="/student/grades"
                className="text-xs font-bold text-blue-600 hover:underline"
              >
                Gradebook &rarr;
              </Link>
            </CardHeader>
            <CardContent className="space-y-2.5 pt-2">
              {student.submissions.length === 0 ? (
                <p className="text-xs text-slate-400 py-4 text-center">
                  Belum ada nilai yang dirilis guru.
                </p>
              ) : (
                student.submissions.map((sub) => (
                  <div
                    key={sub.id}
                    className="p-3 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-between"
                  >
                    <div>
                      <p className="text-xs font-bold text-slate-800">
                        {sub.assignment.title}
                      </p>
                      <p className="text-[11px] text-slate-500">
                        {sub.assignment.teacherSubject.subject.name}
                      </p>
                    </div>
                    <span className="text-base font-black text-blue-600">
                      {sub.score}
                    </span>
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          {/* Latest Learning Materials */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle>Materi Baru</CardTitle>
              <Link
                href="/student/materials"
                className="text-xs font-bold text-blue-600 hover:underline"
              >
                Lihat &rarr;
              </Link>
            </CardHeader>
            <CardContent className="space-y-2.5 pt-2">
              {latestMaterials.slice(0, 3).map((m) => (
                <Link
                  key={m.id}
                  href={`/student/materials?id=${m.id}`}
                  className="block p-3 rounded-xl border border-slate-100 bg-white hover:border-blue-300 hover:bg-slate-50/50 transition-all space-y-1"
                >
                  <div className="flex items-center justify-between">
                    <Badge variant="secondary">{m.subjectName}</Badge>
                    <span className="text-[10px] text-slate-400">
                      {formatDateID(m.createdAt)}
                    </span>
                  </div>
                  <h5 className="text-xs font-bold text-slate-800 line-clamp-1">
                    {m.title}
                  </h5>
                </Link>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
