import type { Metadata } from "next"
import Link from "next/link"
import { BookOpen, PenTool, Library, ArrowRight, UserX } from "lucide-react"
import { getTranslations } from "next-intl/server"

import { getStudentClasses } from "@/modules/classes/data-access"
import { getStudentHomeworkAssignments } from "@/modules/homework/data-access-student"
import { getCurrentStudentUser } from "@/modules/users/data-access"
import { getTextbooks } from "@/modules/textbooks/data-access"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("classes")
  return {
    title: `${t("metadata.studentLearning")} - Next_Edu`,
    description: t("metadata.studentLearning"),
  }
}

export default async function StudentLearningPage() {
  const t = await getTranslations("student")
  await requirePermission(Permissions.CLASS_READ)
  const student = await getCurrentStudentUser()
  if (!student) {
    return (
      <div className="space-y-8">
        <EmptyState title={t("learning.noUser")} description={t("learning.noUserDesc")} icon={UserX} />
      </div>
    )
  }

  const [classes, assignments, textbooks] = await Promise.all([
    getStudentClasses(student.id),
    getStudentHomeworkAssignments(student.id),
    getTextbooks(),
  ])

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

  const cards = [
    {
      title: t("learning.courses"),
      description: t("learning.coursesDesc"),
      icon: BookOpen,
      href: "/student/learning/courses",
      stat: t("learning.enrolled", { count: classes.length }),
    },
    {
      title: t("learning.assignments"),
      description: t("learning.assignmentsDesc"),
      icon: PenTool,
      href: "/student/learning/assignments",
      stat: t("learning.pending", { count: pendingCount }) + (dueSoonCount > 0 ? t("learning.dueSoon", { count: dueSoonCount }) : ""),
    },
    {
      title: t("learning.textbooks"),
      description: t("learning.textbooksDesc"),
      icon: Library,
      href: "/student/learning/textbooks",
      stat: t("learning.available", { count: textbooks.length }),
    },
  ]

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">{t("learning.title")}</h2>
        <p className="text-muted-foreground">{t("learning.description")}</p>
      </div>

      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {cards.map((c) => (
          <Link key={c.href} href={c.href}>
            <Card className="h-full transition-all hover:shadow-md hover:border-primary/50">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-base font-medium">{c.title}</CardTitle>
                <c.icon className="h-5 w-5 text-muted-foreground" />
              </CardHeader>
              <CardContent className="space-y-2">
                <p className="text-sm text-muted-foreground">{c.description}</p>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">{c.stat}</span>
                  <ArrowRight className="h-4 w-4 text-muted-foreground" />
                </div>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  )
}
