import { StudentDashboard } from "@/modules/dashboard/components/student-dashboard/student-dashboard-view"
import { getStudentClasses, getStudentSchedule } from "@/modules/classes/data-access"
import { getDemoStudentUser, getStudentDashboardGrades, getStudentHomeworkAssignments } from "@/modules/homework/data-access"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Inbox } from "lucide-react"

export const dynamic = "force-dynamic"

const toWeekday = (d: Date): 1 | 2 | 3 | 4 | 5 | 6 | 7 => {
  const day = d.getDay()
  return (day === 0 ? 7 : day) as 1 | 2 | 3 | 4 | 5 | 6 | 7
}

export default async function StudentDashboardPage() {
  const student = await getDemoStudentUser()
  if (!student) {
    return (
      <div className="flex h-full flex-col items-center justify-center">
        <EmptyState
          title="No user found"
          description="Create a student user to see dashboard."
          icon={Inbox}
          className="border-none shadow-none h-auto"
        />
      </div>
    )
  }

  const [classes, schedule, assignments, grades] = await Promise.all([
    getStudentClasses(student.id),
    getStudentSchedule(student.id),
    getStudentHomeworkAssignments(student.id),
    getStudentDashboardGrades(student.id),
  ])

  const now = new Date()
  const in7Days = new Date(now)
  in7Days.setDate(in7Days.getDate() + 7)

  const dueSoonCount = assignments.filter((a) => {
    if (!a.dueAt) return false
    const due = new Date(a.dueAt)
    return due >= now && due <= in7Days && a.progressStatus !== "graded"
  }).length

  const overdueCount = assignments.filter((a) => {
    if (!a.dueAt) return false
    const due = new Date(a.dueAt)
    return due < now && a.progressStatus !== "graded"
  }).length

  const gradedCount = assignments.filter((a) => a.progressStatus === "graded").length

  const todayWeekday = toWeekday(now)
  const todayScheduleItems = schedule
    .filter((s) => s.weekday === todayWeekday)
    .map((s) => ({
      id: s.id,
      classId: s.classId,
      className: s.className,
      course: s.course,
      startTime: s.startTime,
      endTime: s.endTime,
      location: s.location ?? null,
    }))
    .sort((a, b) => a.startTime.localeCompare(b.startTime))

  const upcomingAssignments = [...assignments]
    .sort((a, b) => {
      const aDue = a.dueAt ? new Date(a.dueAt).getTime() : Number.POSITIVE_INFINITY
      const bDue = b.dueAt ? new Date(b.dueAt).getTime() : Number.POSITIVE_INFINITY
      return aDue - bDue
    })
    .slice(0, 6)

  return (
    <StudentDashboard
      studentName={student.name}
      enrolledClassCount={classes.length}
      dueSoonCount={dueSoonCount}
      overdueCount={overdueCount}
      gradedCount={gradedCount}
      todayScheduleItems={todayScheduleItems}
      upcomingAssignments={upcomingAssignments}
      grades={grades}
    />
  )
}
