import type { Metadata } from "next";
import { requirePermission, sessionCan } from "@/lib/auth/session";
import { prisma } from "@/lib/prisma";
import { StatCard } from "@/components/ui/StatCard";
import { Icon } from "@/components/ui/Icon";
import { NAV_ITEMS } from "@/lib/navigation";
import { isPersonnelManager } from "@/lib/personnel/access";
import { getMyDay, startOfDay, endOfDay } from "@/lib/dashboard/queries";
import { QuickAccess } from "./QuickAccess";

export const metadata: Metadata = { title: "Dashboard" };

// Tagesaktuelle Daten — nicht statisch vorrendern.
export const dynamic = "force-dynamic";

function greeting(): string {
  const h = new Date().getHours();
  if (h < 11) return "Guten Morgen";
  if (h < 18) return "Hallo";
  return "Guten Abend";
}

export default async function DashboardPage() {
  const session = await requirePermission("dashboard.view");
  const userId = session.user.id;
  const perms = session.user.permissions;
  const canSeeAllAbsences = sessionCan(session, "absences.view_all");

  const [openTasks, activeProjects, meetingsToday, pendingAbsences, myDay] = await Promise.all([
    prisma.task.count({ where: { assignees: { some: { userId } }, archivedAt: null } }),
    prisma.project.count({ where: { status: "ACTIVE" } }),
    prisma.meeting.count({ where: { startAt: { gte: startOfDay(), lte: endOfDay() } } }),
    prisma.absenceRequest.count({
      where: canSeeAllAbsences ? { status: "PENDING" } : { status: "PENDING", userId },
    }),
    getMyDay(userId),
  ]);

  const firstName = (session.user.name ?? "").split(" ")[0] || "willkommen";
  const today = new Date().toLocaleDateString("de-DE", {
    weekday: "long",
    day: "2-digit",
    month: "long",
    year: "numeric",
  });

  const canPersonnel = await isPersonnelManager(userId, perms);
  const quickAccess = NAV_ITEMS.filter(
    (i) =>
      i.href !== "/dashboard" &&
      (i.anyOf.some((p) => perms.includes(p)) || (i.href === "/personnel" && canPersonnel)),
  ).map(({ href, label, icon }) => ({ href, label, icon }));

  const stats = [
    { label: "Offene Aufgaben", value: openTasks, icon: "kanban", glow: "var(--blue)", hint: "Dir zugewiesen" },
    { label: "Aktive Projekte", value: activeProjects, icon: "projects", glow: "var(--violet)", hint: "Organisationsweit" },
    { label: "Meetings heute", value: meetingsToday, icon: "meetings", glow: "var(--pink)", hint: "Im Tageskalender" },
    {
      label: canSeeAllAbsences ? "Offene Anträge" : "Meine Anträge",
      value: pendingAbsences,
      icon: "absences",
      glow: "var(--cyan)",
      hint: "Wartet auf Freigabe",
    },
  ];

  return (
    <div className="flex flex-col gap-5">
      {/* Hero */}
      <section
        className="card relative overflow-hidden"
        data-reveal
        style={{ padding: "clamp(24px, 3.5vw, 44px)" }}
      >
        <div
          aria-hidden
          className="pointer-events-none absolute -right-24 -top-24 h-72 w-72 rounded-full"
          style={{
            background: "radial-gradient(circle, rgba(158,215,255,.28), rgba(255,159,215,.14) 50%, transparent 72%)",
            filter: "blur(10px)",
          }}
        />
        <div className="relative flex flex-col gap-3">
          <span className="eyebrow">{today}</span>
          <h1>
            {greeting()}, <span className="gradient-text">{firstName}</span> 👋
          </h1>
          <p className="text-muted max-w-[62ch]">
            Dein zentraler Überblick über Aufgaben, Projekte, Termine und
            Abwesenheiten im Avaria-Team.
          </p>
        </div>
      </section>

      {/* Statistik-Karten */}
      <section className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {stats.map((s, i) => (
          <StatCard key={s.label} {...s} delay={i * 70} />
        ))}
      </section>

      <section className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        <QuickAccess modules={quickAccess} userId={userId} />

        <div className="card flex flex-col gap-3" data-reveal data-reveal-delay={120}>
          <div className="flex items-center justify-between gap-2">
            <h2>Mein Tag</h2>
            {myDay.length > 0 ? <span className="badge">{myDay.length}</span> : null}
          </div>

          {myDay.length === 0 ? (
            <div
              className="rounded-2xl border px-4 py-4 text-sm"
              style={{ borderColor: "var(--line)", background: "rgba(13,19,42,.4)" }}
            >
              <div className="flex items-center gap-2 font-bold">
                <span
                  className="inline-block h-2 w-2 rounded-full"
                  style={{ background: "var(--blue)", boxShadow: "0 0 10px 1px rgba(158,215,255,.7)" }}
                />
                Nichts Dringendes
              </div>
              <p className="text-muted mt-1">
                Keine Termine, Deadlines oder offenen Punkte für heute.
              </p>
            </div>
          ) : (
            <div className="flex max-h-[340px] flex-col gap-2 overflow-y-auto pr-0.5">
              {myDay.map((item) => (
                <a
                  key={item.id}
                  href={item.href}
                  className="flex items-center gap-3 rounded-2xl border px-3 py-2.5 transition-colors hover:bg-[rgba(158,215,255,.06)]"
                  style={{
                    borderColor: item.urgent ? "rgba(255,159,215,.35)" : "var(--line)",
                    background: "rgba(13,19,42,.4)",
                  }}
                >
                  <span
                    className="grid h-9 w-9 shrink-0 place-items-center rounded-xl"
                    style={{ background: item.accent, color: "#0a0e22" }}
                  >
                    <Icon name={item.icon} size={17} />
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-sm font-bold">{item.title}</span>
                    {item.subtitle ? (
                      <span className="block truncate text-xs text-muted">{item.subtitle}</span>
                    ) : null}
                  </span>
                  <span
                    className="shrink-0 text-xs font-black"
                    style={{ color: item.urgent ? "var(--pink)" : "var(--muted)" }}
                  >
                    {item.time}
                  </span>
                </a>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
