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 { AuditPanel } from "../../components/audit-panel";
import { ProjectActions } from "../project-actions";

function formatMinutes(minutes: number) {
  const hours = Math.floor(minutes / 60);
  const rest = minutes % 60;
  return `${hours}h ${rest}m`;
}

export default async function ProjectDetailPage({ params }: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  const projectWhere = session?.user.systemRole === "SYSTEM_ADMIN" ? { id: params.id } : { id: params.id, organizationId: session?.user.organizationId! };
  const entryWhere = session?.user.systemRole === "SYSTEM_ADMIN" ? { projectId: params.id } : { projectId: params.id, organizationId: session?.user.organizationId! };
  const [project, totals, recentEntries] = await Promise.all([
    prisma.project.findFirst({
      where: projectWhere,
      include: {
        organization: { select: { name: true } },
        users: { include: { team: true }, orderBy: { name: "asc" } },
        _count: { select: { timeEntries: true } }
      }
    }),
    prisma.timeEntry.aggregate({ where: entryWhere, _sum: { durationMinutes: true } }),
    prisma.timeEntry.findMany({
      where: entryWhere,
      take: 10,
      orderBy: { startAt: "desc" },
      include: { user: { select: { name: true, email: true } } }
    }),
  ]);
  if (!project) notFound();

  return (
    <div>
      <Link className="text-sm font-semibold text-brand-secondary" href="/admin/projects">Back to projects</Link>
      <div className="mt-3 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-3xl font-semibold">{project.name}</h1>
          <p className="mt-2 text-slate-600">{project.organization.name} · {project.isArchived ? "Archived" : "Active"}</p>
        </div>
        <ProjectActions id={project.id} isDefault={project.isDefault} />
      </div>

      <section className="mt-6 grid gap-4 md:grid-cols-3">
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <p className="text-sm text-slate-500">Assigned users</p>
          <p className="mt-2 text-2xl font-semibold">{project.users.length}</p>
        </div>
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <p className="text-sm text-slate-500">Time entries</p>
          <p className="mt-2 text-2xl font-semibold">{project._count.timeEntries}</p>
        </div>
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <p className="text-sm text-slate-500">Tracked time</p>
          <p className="mt-2 text-2xl font-semibold">{formatMinutes(totals._sum.durationMinutes ?? 0)}</p>
        </div>
      </section>

      <section className="mt-6 grid gap-5 lg:grid-cols-2">
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <h2 className="text-lg font-semibold">Assigned users</h2>
          <div className="mt-4 grid gap-2">
            {project.users.length ? project.users.map((user) => (
              <div className="rounded-lg bg-brand-paper p-3" key={user.id}>
                <p className="font-medium">{user.name ?? user.email}</p>
                <p className="text-sm text-slate-500">{user.email} · {user.team?.name ?? "No team"}</p>
              </div>
            )) : <p className="text-sm text-slate-500">No users are assigned 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 time entries</h2>
          <div className="mt-4 grid gap-2">
            {recentEntries.length ? recentEntries.map((entry) => (
              <div className="rounded-lg bg-brand-paper p-3" key={entry.id}>
                <p className="font-medium">{entry.user.name ?? entry.user.email}</p>
                <p className="text-sm text-slate-500">{entry.startAt.toLocaleString()} · {entry.isRunning ? "Running" : formatMinutes(entry.durationMinutes)}</p>
              </div>
            )) : <p className="text-sm text-slate-500">No time entries have been recorded for this project.</p>}
          </div>
        </div>
      </section>

      <AuditPanel targetId={project.id} targetType="project" title="Project audit events" />
    </div>
  );
}
