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";

function formatDateTime(date: Date) {
  return new Intl.DateTimeFormat("en", {
    dateStyle: "medium",
    timeStyle: "short"
  }).format(date);
}

export default async function ScreenshotDetailsPage({ params }: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  const systemAdmin = session?.user.systemRole === "SYSTEM_ADMIN";
  const organizationId = session?.user.organizationId;
  const screenshot = await prisma.screenshot.findFirst({
    where: { id: params.id, ...(systemAdmin ? {} : { organizationId: organizationId! }) },
    include: {
      user: { include: { team: true } },
      timeEntry: { include: { project: true } }
    }
  });
  if (!screenshot) notFound();

  return (
    <div>
      <Link className="text-sm font-semibold text-brand-secondary" href="/admin/screenshots">Back to screenshots</Link>
      <div className="mt-3 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-3xl font-semibold">Screenshot detail</h1>
          <p className="mt-2 text-slate-600">{screenshot.user.name ?? screenshot.user.email} · {formatDateTime(screenshot.capturedAt)}</p>
        </div>
        {screenshot.localPath || screenshot.previewUrl ? (
          <div className="flex flex-wrap gap-2">
            <a className="brand-button-secondary" href={`/api/screenshots/${screenshot.id}/image`} rel="noreferrer" target="_blank">Open original</a>
            <a className="brand-button" download href={`/api/screenshots/${screenshot.id}/image?download=1`}>Download</a>
          </div>
        ) : null}
      </div>

      <section className="mt-6 overflow-hidden rounded-lg border border-brand-primary/20 bg-white shadow-sm">
        <div className="flex min-h-[320px] items-center justify-center bg-slate-100">
          {screenshot.localPath || screenshot.previewUrl ? (
            <img alt={`Screenshot captured for ${screenshot.user.name ?? screenshot.user.email}`} className="max-h-[72vh] w-full object-contain" src={`/api/screenshots/${screenshot.id}/image`} />
          ) : (
            <span className="text-sm text-slate-500">No preview available</span>
          )}
        </div>
        <div className="grid gap-3 p-5 text-sm md:grid-cols-2">
          <p><span className="font-semibold">Employee:</span> {screenshot.user.name ?? screenshot.user.email}</p>
          <p><span className="font-semibold">Email:</span> {screenshot.user.email}</p>
          <p><span className="font-semibold">Team:</span> {screenshot.user.team?.name ?? "No team"}</p>
          <p><span className="font-semibold">Project:</span> {screenshot.timeEntry.project?.name ?? "No project"}</p>
          <p><span className="font-semibold">Captured:</span> {formatDateTime(screenshot.capturedAt)}</p>
          <p><span className="font-semibold">Object key:</span> {screenshot.objectKey}</p>
          <p><span className="font-semibold">Session start:</span> {formatDateTime(screenshot.timeEntry.startAt)}</p>
          <p><span className="font-semibold">Session end:</span> {screenshot.timeEntry.endAt ? formatDateTime(screenshot.timeEntry.endAt) : "Running"}</p>
        </div>
      </section>
      <AuditPanel targetId={screenshot.id} targetType="screenshot" title="Screenshot audit events" />
    </div>
  );
}
