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 Link from "next/link";
import { redirect } from "next/navigation";
import {
  BookOpen,
  User,
  Clock,
  Layers,
  ClipboardList,
  FileCheck,
  ChevronRight,
} from "lucide-react";

export default async function StudentSubjectsPage() {
  const user = await getSessionUser();
  if (!user || user.role !== "STUDENT") redirect("/login");

  let subjectsData: any[] = [];
  let studentClass = null;

  if (user.studentId) {
    const student = await prisma.student.findUnique({
      where: { id: user.studentId },
      include: {
        classMembers: {
          include: {
            class: {
              include: {
                teacherSubjects: {
                  include: {
                    subject: true,
                    teacher: true,
                    schedules: true,
                    _count: {
                      select: {
                        materials: true,
                        assignments: true,
                        quizzes: true,
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
    });

    studentClass = student?.classMembers[0]?.class;
    if (studentClass) {
      subjectsData = studentClass.teacherSubjects;
    }
  }

  // Fallback if testing as student with no enrolled subjects yet
  if (subjectsData.length === 0) {
    const defaultClass = await prisma.class.findFirst({
      where: { name: "X.1" },
      include: {
        teacherSubjects: {
          include: {
            subject: true,
            teacher: true,
            schedules: true,
            _count: {
              select: {
                materials: true,
                assignments: true,
                quizzes: true,
              },
            },
          },
        },
      },
    });
    if (defaultClass) {
      studentClass = defaultClass;
      subjectsData = defaultClass.teacherSubjects;
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Mata Pelajaran Terdaftar"
        description={`Katalog mata pelajaran semester ini untuk Kelas ${studentClass?.name || "X.1"}. Akses materi belajar, tugas, dan kuis secara terpadu.`}
        breadcrumbs={[
          { label: "Siswa", href: "/student/dashboard" },
          { label: "Mata Pelajaran" },
        ]}
      />

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {subjectsData.map((ts) => {
          const schedule = ts.schedules[0];
          return (
            <Card key={ts.id} className="overflow-hidden hover:shadow-md transition-shadow group">
              <div className="bg-gradient-to-r from-blue-700 to-indigo-800 p-4 text-white">
                <div className="flex items-center justify-between">
                  <Badge variant="secondary" className="bg-white/20 text-white border-none font-bold">
                    {ts.subject.code}
                  </Badge>
                  <span className="text-[11px] text-blue-100 font-mono">
                    Kelas {studentClass?.name}
                  </span>
                </div>
                <h3 className="text-lg font-bold mt-2 truncate">{ts.subject.name}</h3>
                <div className="flex items-center gap-1.5 text-xs text-blue-100 mt-1">
                  <User className="h-3.5 w-3.5 text-blue-200" />
                  <span className="truncate">{ts.teacher.fullName}</span>
                </div>
              </div>

              <CardContent className="p-4 space-y-4">
                {/* Schedule info */}
                <div className="flex items-center gap-2 text-xs text-slate-600">
                  <Clock className="h-4 w-4 text-slate-400 shrink-0" />
                  {schedule ? (
                    <span>
                      {schedule.dayOfWeek}, {schedule.startTime} - {schedule.endTime} (Ruang {schedule.room})
                    </span>
                  ) : (
                    <span className="text-slate-400">Jadwal belum ditentukan</span>
                  )}
                </div>

                {/* Counters */}
                <div className="grid grid-cols-3 gap-2 py-2 border-y border-slate-100 text-center">
                  <div>
                    <span className="text-[10px] text-slate-500">Materi</span>
                    <p className="text-sm font-bold text-blue-600">
                      {ts._count.materials}
                    </p>
                  </div>
                  <div>
                    <span className="text-[10px] text-slate-500">Tugas</span>
                    <p className="text-sm font-bold text-purple-600">
                      {ts._count.assignments}
                    </p>
                  </div>
                  <div>
                    <span className="text-[10px] text-slate-500">Kuis/Ujian</span>
                    <p className="text-sm font-bold text-emerald-600">
                      {ts._count.quizzes}
                    </p>
                  </div>
                </div>

                {/* Action buttons */}
                <div className="grid grid-cols-2 gap-2 pt-1">
                  <Link href={`/student/materials?subjectId=${ts.subjectId}`}>
                    <Button variant="outline" size="sm" className="w-full text-xs">
                      <BookOpen className="h-3.5 w-3.5 mr-1" />
                      Materi
                    </Button>
                  </Link>
                  <Link href={`/student/assignments?subjectId=${ts.subjectId}`}>
                    <Button variant="outline" size="sm" className="w-full text-xs">
                      <ClipboardList className="h-3.5 w-3.5 mr-1" />
                      Tugas
                    </Button>
                  </Link>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
