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 { formatDateID } from "@/lib/utils";
import { Users, CheckCircle2, AlertCircle, Clock } from "lucide-react";

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

  const records = await prisma.attendanceRecord.findMany({
    where: { studentId: user.studentId },
    include: {
      attendance: {
        include: {
          teacherSubject: {
            include: {
              subject: true,
              teacher: true,
            },
          },
        },
      },
    },
    orderBy: { createdAt: "desc" },
  });

  const totalSessions = records.length;
  const presentCount = records.filter((r) => r.status === "PRESENT").length;
  const sickCount = records.filter((r) => r.status === "SICK").length;
  const permCount = records.filter((r) => r.status === "PERMISSION").length;
  const absentCount = records.filter((r) => r.status === "ABSENT").length;

  const percentage = totalSessions > 0 ? Math.round((presentCount / totalSessions) * 100) : 100;

  return (
    <div className="space-y-6">
      <PageHeader
        title="Riwayat Presensi Kehadiran"
        description="Rekapitulasi kehadiran Anda pada seluruh sesi pertemuan mata pelajaran."
        breadcrumbs={[
          { label: "Dashboard", href: "/student/dashboard" },
          { label: "Presensi Saya" },
        ]}
      />

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
        <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm text-center">
          <span className="text-[11px] text-slate-500 block">Tingkat Hadir</span>
          <span className="text-3xl font-black text-blue-600 block mt-1">
            {percentage}%
          </span>
          <span className="text-[10px] text-emerald-600 font-semibold">Sangat Baik</span>
        </div>
        <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm text-center">
          <span className="text-[11px] text-slate-500 block">Hadir (H)</span>
          <span className="text-3xl font-black text-emerald-600 block mt-1">
            {presentCount}
          </span>
          <span className="text-[10px] text-slate-400">Pertemuan</span>
        </div>
        <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm text-center">
          <span className="text-[11px] text-slate-500 block">Sakit (S)</span>
          <span className="text-3xl font-black text-amber-600 block mt-1">
            {sickCount}
          </span>
          <span className="text-[10px] text-slate-400">Pertemuan</span>
        </div>
        <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm text-center">
          <span className="text-[11px] text-slate-500 block">Izin (I)</span>
          <span className="text-3xl font-black text-cyan-600 block mt-1">
            {permCount}
          </span>
          <span className="text-[10px] text-slate-400">Pertemuan</span>
        </div>
        <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm text-center">
          <span className="text-[11px] text-slate-500 block">Alpa (A)</span>
          <span className="text-3xl font-black text-rose-600 block mt-1">
            {absentCount}
          </span>
          <span className="text-[10px] text-slate-400">Pertemuan</span>
        </div>
      </div>

      {/* Detail Table */}
      <Card>
        <CardHeader className="pb-3 border-b border-slate-100">
          <CardTitle>Riwayat Pertemuan Terdata</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-xs text-left">
              <thead className="bg-slate-50 text-slate-600 font-bold border-b border-slate-200">
                <tr>
                  <th className="py-3 px-4">Tanggal</th>
                  <th className="py-3 px-4">Mata Pelajaran</th>
                  <th className="py-3 px-4">Pertemuan</th>
                  <th className="py-3 px-4">Topik Pembahasan</th>
                  <th className="py-3 px-4">Status</th>
                  <th className="py-3 px-4">Keterangan</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {records.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-8 text-center text-slate-400">
                      Belum ada catatan presensi pertemuan.
                    </td>
                  </tr>
                ) : (
                  records.map((r) => {
                    let badgeVariant: any = "success";
                    let badgeLabel = "Hadir";
                    if (r.status === "SICK") {
                      badgeVariant = "warning";
                      badgeLabel = "Sakit";
                    } else if (r.status === "PERMISSION") {
                      badgeVariant = "secondary";
                      badgeLabel = "Izin";
                    } else if (r.status === "ABSENT") {
                      badgeVariant = "danger";
                      badgeLabel = "Alpa";
                    }

                    return (
                      <tr key={r.id} className="hover:bg-slate-50 transition-colors">
                        <td className="py-3 px-4 font-mono text-slate-600">
                          {formatDateID(r.attendance.date)}
                        </td>
                        <td className="py-3 px-4 font-bold text-slate-900">
                          {r.attendance.teacherSubject.subject.name}
                        </td>
                        <td className="py-3 px-4 font-semibold text-slate-700">
                          Ke-{r.attendance.meetingNumber}
                        </td>
                        <td className="py-3 px-4 text-slate-600 max-w-xs truncate">
                          {r.attendance.topic || "-"}
                        </td>
                        <td className="py-3 px-4">
                          <Badge variant={badgeVariant}>{badgeLabel}</Badge>
                        </td>
                        <td className="py-3 px-4 text-slate-500 italic">
                          {r.note || "-"}
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
