import Link from "next/link";
import { getServerSession } from "next-auth";
import { notFound } from "next/navigation";
import { authOptions } from "../../../lib/auth/options";
import { prisma } from "../../../lib/db/prisma";
import { UserEditForm } from "../user-edit-form";

export default async function UserDetailsPage({ params }: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  const systemAdmin = session?.user.systemRole === "SYSTEM_ADMIN";
  const organizationId = session?.user.organizationId;
  const baseWhere = systemAdmin ? {} : { organizationId: organizationId! };

  const [user, roles, teams, projects, auditLogs, timeEntries, screenshots, adhocRecords] = await Promise.all([
    prisma.user.findFirst({
      where: { id: params.id, ...baseWhere },
      include: { roles: true, team: true, projects: true }
    }),
    prisma.role.findMany({ where: baseWhere, orderBy: { name: "asc" } }),
    prisma.team.findMany({ where: baseWhere, orderBy: { name: "asc" } }),
    prisma.project.findMany({ where: { ...baseWhere, isArchived: false }, orderBy: { name: "asc" } }),
    prisma.auditLog.findMany({
      where: { ...baseWhere, OR: [{ actorUserId: params.id }, { targetId: params.id }] },
      orderBy: { createdAt: "desc" },
      take: 20
    }),
    prisma.timeEntry.findMany({
      where: { ...baseWhere, userId: params.id },
      include: { project: { select: { name: true } } },
      orderBy: { startAt: "desc" },
      take: 10
    }),
    prisma.screenshot.findMany({
      where: { ...baseWhere, userId: params.id },
      orderBy: { capturedAt: "desc" },
      take: 6
    }),
    prisma.adhocRecord.findMany({
      where: { ...baseWhere, userId: params.id },
      orderBy: { createdAt: "desc" },
      take: 10
    })
  ]);
  if (!user) notFound();

  return (
    <div>
      <Link className="text-sm font-semibold text-brand-secondary" href="/admin/users">Back to users</Link>
      <h1 className="mt-3 text-3xl font-semibold">{user.name ?? user.email}</h1>
      <p className="mt-2 text-slate-600">{user.email} · {user.status}</p>
      <UserEditForm projects={projects} roles={roles} teams={teams} user={user} />
      <section className="mt-6 grid gap-5 lg:grid-cols-3">
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <h2 className="text-lg font-semibold">Recent time</h2>
          <div className="mt-4 grid gap-2 text-sm">
            {timeEntries.length ? timeEntries.map((entry) => (
              <div className="rounded-lg bg-brand-paper p-3" key={entry.id}>
                <p className="font-medium">{entry.project?.name ?? "No project"}</p>
                <p className="text-xs text-slate-500">{entry.startAt.toLocaleString()} · {entry.isRunning ? "Running" : `${entry.durationMinutes} min`}</p>
              </div>
            )) : <p className="text-slate-500">No time entries yet.</p>}
          </div>
        </div>
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <h2 className="text-lg font-semibold">Recent screenshots</h2>
          <div className="mt-4 grid grid-cols-2 gap-2 text-sm">
            {screenshots.length ? screenshots.map((shot) => (
              <Link className="overflow-hidden rounded-lg bg-brand-paper" href={`/admin/screenshots/${shot.id}`} key={shot.id}>
                {shot.previewUrl ? <img alt="User screenshot" className="h-24 w-full object-cover" src={shot.previewUrl} /> : <div className="grid h-24 place-items-center text-xs text-slate-500">No preview</div>}
              </Link>
            )) : <p className="text-slate-500">No screenshots yet.</p>}
          </div>
        </div>
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <h2 className="text-lg font-semibold">Adhoc records</h2>
          <div className="mt-4 grid gap-2 text-sm">
            {adhocRecords.length ? adhocRecords.map((record) => (
              <div className="rounded-lg bg-brand-paper p-3" key={record.id}>
                <p className="font-medium">{record.hours.toString()} hours · {record.status}</p>
                <p className="text-xs text-slate-500">{record.date.toLocaleDateString()} · {record.reason}</p>
              </div>
            )) : <p className="text-slate-500">No adhoc records yet.</p>}
          </div>
        </div>
      </section>
      <section className="mt-6 rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
        <h2 className="text-lg font-semibold">Recent audit activity</h2>
        <div className="mt-4 grid gap-2 text-sm">
          {auditLogs.length ? auditLogs.map((log) => (
            <div className="rounded-lg bg-brand-paper p-3 dark:bg-slate-900" key={log.id}>
              <p className="font-medium">{log.action}</p>
              <p className="text-xs text-slate-500">{log.createdAt.toISOString()} · {log.targetType ?? "record"}</p>
            </div>
          )) : <p className="text-slate-500">No audit activity yet.</p>}
        </div>
      </section>
    </div>
  );
}
