import type { Metadata } from "next";
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
import { prisma } from "@/lib/prisma"
import { redirect } from "next/navigation"
import { BookOpen, Users, AlertTriangle, Clock } from "lucide-react"
import Link from "next/link"

export const metadata: Metadata = {
  title: "Overview | Admin | E-Library",
  description: "Admin dashboard overview for Federal Polytechnic Bali E-Library.",
};

export default async function AdminOverviewPage() {
  const session = await auth.api.getSession({ headers: await headers() })
  if (!session) redirect("/login")

  const user = await prisma.user.findUnique({ where: { id: session.user.id } })
  if (!user) redirect("/login")

  const [
    totalBooks,
    totalUsers,
    overdueLoans,
    unpickedReservations,
    recentLoans,
  ] = await Promise.all([
    prisma.book.count(),
    prisma.user.count({ where: { role: "STUDENT" } }),
    prisma.loan.count({
      where: {
        status: "ACTIVE",
        dueDate: { lt: new Date() }
      }
    }),
    prisma.reservation.count({
      where: { status: "PENDING" }
    }),
    prisma.loan.findMany({
      take: 5,
      orderBy: { borrowedAt: "desc" },
      include: {
        book: { select: { title: true } },
        user: { select: { name: true, studentId: true } },
      }
    })
  ])

  const stats = [
    {
      label: "Total Books",
      value: totalBooks,
      icon: BookOpen,
      href: "/admin/books",
      color: "text-blue-500",
      bg: "bg-blue-500/10",
      border: "border-blue-500/20",
    },
    {
      label: "Total Students",
      value: totalUsers,
      icon: Users,
      href: "/admin/users",
      color: "text-emerald-500",
      bg: "bg-emerald-500/10",
      border: "border-emerald-500/20",
    },
    {
      label: "Overdue Loans",
      value: overdueLoans,
      icon: AlertTriangle,
      href: "/admin/loans",
      color: "text-red-500",
      bg: "bg-red-500/10",
      border: "border-red-500/20",
      urgent: overdueLoans > 0,
    },
    {
      label: "Pending Pickups",
      value: unpickedReservations,
      icon: Clock,
      href: "/admin/loans?tab=reservations",
      color: "text-amber-500",
      bg: "bg-amber-500/10",
      border: "border-amber-500/20",
      urgent: unpickedReservations > 0,
    },
  ]

  return (
    <main className="flex-1 space-y-8 p-4 md:p-8">

      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Overview</h1>
        <p className="text-muted-foreground mt-1">
          Welcome back, {user.name?.split(" ")[0]}. Here{"'"}s what needs your attention.
        </p>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => {
          const Icon = stat.icon
          return (
            <Link
              key={stat.label}
              href={stat.href}
              className={`
                relative flex flex-col gap-4 p-6 rounded-2xl border 
                transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md
                bg-card ${stat.border}
                ${stat.urgent ? "ring-2 ring-offset-2 ring-offset-background " + stat.border : ""}
              `}
            >
              {stat.urgent && (
                <span className="absolute top-3 right-3 size-2 rounded-full bg-current animate-pulse" 
                  style={{ color: stat.color.replace("text-", "") }} 
                />
              )}
              <div className={`flex items-center justify-center size-12 rounded-xl ${stat.bg}`}>
                <Icon className={`size-6 ${stat.color}`} />
              </div>
              <div>
                <p className="text-4xl font-bold tracking-tight">{stat.value}</p>
                <p className="text-sm text-muted-foreground mt-1">{stat.label}</p>
              </div>
            </Link>
          )
        })}
      </div>

      {/* Recent Activity */}
      <div className="rounded-2xl border bg-card">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="font-semibold">Recent Loans</h2>
          <Link
            href="/admin/loans"
            className="text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            View all →
          </Link>
        </div>

        <div className="divide-y">
          {recentLoans.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">
              No loans yet.
            </p>
          ) : (
            recentLoans.map((loan) => {
              const isOverdue = loan.dueDate < new Date() && loan.status === "ACTIVE"
              return (
                <div key={loan.id} className="flex items-center justify-between px-6 py-4">
                  <div className="flex flex-col gap-0.5">
                    <p className="text-sm font-medium line-clamp-1">{loan.book.title}</p>
                    <p className="text-xs text-muted-foreground">
                      {loan.user.name} · {loan.user.studentId ?? ""}
                    </p>
                  </div>
                  <div className="text-right shrink-0 ml-4">
                    <p className={`text-xs font-medium ${isOverdue ? "text-red-500" : "text-muted-foreground"}`}>
                      {isOverdue ? "Overdue" : "Active"}
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Due {new Date(loan.dueDate).toLocaleDateString()}
                    </p>
                  </div>
                </div>
              )
            })
          )}
        </div>
      </div>

    </main>
  )
}