import { getServerSession } from "next-auth";
import { Prisma } from "@prisma/client";
import Link from "next/link";
import { authOptions } from "../../lib/auth/options";
import { prisma } from "../../lib/db/prisma";
import { EmptyState } from "../../components/empty-state";
import { toDateInput } from "../../lib/ui/format";

function dateRange(searchParams: { from?: string; to?: string }) {
  const to = searchParams.to ? new Date(`${searchParams.to}T23:59:59.999Z`) : new Date();
  const from = searchParams.from
    ? new Date(`${searchParams.from}T00:00:00.000Z`)
    : new Date(to.getTime() - 6 * 24 * 60 * 60 * 1000);
  return { from, to };
}

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

function pageHref(searchParams: { userId?: string; from?: string; to?: string }, cursor: string) {
  const params = new URLSearchParams();
  if (searchParams.userId) params.set("userId", searchParams.userId);
  if (searchParams.from) params.set("from", searchParams.from);
  if (searchParams.to) params.set("to", searchParams.to);
  params.set("cursor", cursor);
  return `/admin/screenshots?${params.toString()}`;
}

export default async function AdminScreenshotsPage({
  searchParams
}: {
  searchParams: { userId?: string; from?: string; to?: string; cursor?: string };
}) {
  const session = await getServerSession(authOptions);
  const systemAdmin = session?.user.systemRole === "SYSTEM_ADMIN";
  const organizationId = session?.user.organizationId;
  const { from, to } = dateRange(searchParams);
  const tenantWhere = systemAdmin ? {} : { organizationId: organizationId! };
  const selectedUserId = searchParams.userId || "";
  const pageSize = 30;
  const where: Prisma.ScreenshotWhereInput = {
    ...tenantWhere,
    capturedAt: { gte: from, lte: to },
    ...(selectedUserId ? { userId: selectedUserId } : {})
  };

  const [screenshots, users] = await Promise.all([
    prisma.screenshot.findMany({
      where,
      include: {
        user: { select: { id: true, name: true, email: true, team: { select: { name: true } } } },
        timeEntry: { select: { startAt: true, endAt: true, project: { select: { name: true } } } }
      },
      orderBy: { capturedAt: "desc" },
      take: pageSize + 1,
      ...(searchParams.cursor ? { cursor: { id: searchParams.cursor }, skip: 1 } : {})
    }),
    prisma.user.findMany({
      where: tenantWhere,
      select: { id: true, name: true, email: true },
      orderBy: { name: "asc" }
    })
  ]);
  const hasNextPage = screenshots.length > pageSize;
  const visibleScreenshots = hasNextPage ? screenshots.slice(0, pageSize) : screenshots;
  const nextCursor = visibleScreenshots.at(-1)?.id;

  return (
    <div>
      <div className="admin-card p-6">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-sm font-semibold uppercase tracking-wide text-brand-primary">Evidence timeline</p>
            <h1 className="mt-1 text-3xl font-semibold">Screenshots</h1>
            <p className="mt-2 text-slate-600">Review captured screenshots by employee and date range.</p>
          </div>
          <span className="rounded-lg bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-200">
            {visibleScreenshots.length}{hasNextPage ? "+" : ""} captured
          </span>
        </div>
      </div>

      <form className="admin-card mt-6 grid gap-3 p-4 md:grid-cols-[1fr_180px_180px_auto]">
        <label className="admin-label">
          Employee
          <select className="admin-input" name="userId" defaultValue={selectedUserId}>
            <option value="">All employees</option>
            {users.map((user) => (
              <option key={user.id} value={user.id}>{user.name ?? user.email}</option>
            ))}
          </select>
        </label>
        <label className="admin-label">
          From
          <input className="admin-input" name="from" type="date" defaultValue={toDateInput(from)} />
        </label>
        <label className="admin-label">
          To
          <input className="admin-input" name="to" type="date" defaultValue={toDateInput(to)} />
        </label>
        <button className="brand-button self-end" type="submit">Apply</button>
      </form>

      <section className="mt-6">
        {visibleScreenshots.length ? (
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {visibleScreenshots.map((shot) => (
              <article className="admin-card overflow-hidden" key={shot.id}>
                <div className="flex aspect-video items-center justify-center bg-slate-100 dark:bg-slate-950">
                  {shot.localPath || shot.previewUrl ? (
                    <img alt={`Screenshot captured for ${shot.user.name ?? shot.user.email}`} className="h-full w-full object-cover" src={`/api/screenshots/${shot.id}/image`} />
                  ) : (
                    <span className="text-sm text-slate-500">No preview available</span>
                  )}
                </div>
                <div className="grid gap-3 p-4 text-sm">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="truncate font-semibold">{shot.user.name ?? shot.user.email}</p>
                      <p className="truncate text-slate-500">{shot.user.email}</p>
                    </div>
                    <span className="rounded-lg bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-500 dark:bg-slate-800">{shot.user.team?.name ?? "No team"}</span>
                  </div>
                  <div className="grid gap-1 text-slate-600">
                    <p>Captured: {formatDateTime(shot.capturedAt)}</p>
                    <p>Project: {shot.timeEntry.project?.name ?? "No project"}</p>
                    <p>Session: {formatDateTime(shot.timeEntry.startAt)} - {shot.timeEntry.endAt ? formatDateTime(shot.timeEntry.endAt) : "Running"}</p>
                  </div>
                  <Link className="brand-button-secondary" href={`/admin/screenshots/${shot.id}`}>View detail</Link>
                </div>
              </article>
            ))}
          </div>
        ) : (
          <div className="admin-card p-8">
            <EmptyState title="No screenshots found" description="Try a different employee or date range, or confirm the desktop app has Screen Recording permission." />
          </div>
        )}
      </section>
      {hasNextPage && nextCursor ? (
        <div className="mt-6 flex justify-center">
          <Link className="brand-button-secondary" href={pageHref(searchParams, nextCursor)}>Load older screenshots</Link>
        </div>
      ) : null}
    </div>
  );
}
