import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";
import { TasksPageClient } from "./TasksPageClient";

export const metadata = { title: "My Tasks" };

export default async function TasksPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; assignee?: string }>;
}) {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (session.user.role === "CLIENT") redirect("/dashboard");

  const { status, assignee } = await searchParams;
  const isArtist = session.user.role === "ARTIST";

  // Artists only see their own tasks; others can filter by assignee
  const assigneeFilter = isArtist
    ? session.user.id
    : assignee || undefined;

  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  const tasks = await db.task.findMany({
    where: {
      ...(assigneeFilter ? { assignedArtistId: assigneeFilter } : {}),
    },
    orderBy: [{ dueDate: "asc" }, { priority: "desc" }, { createdAt: "desc" }],
    include: {
      shot: { select: { id: true, shotCode: true } },
      asset: { select: { id: true, assetCode: true, name: true } },
      project: { select: { id: true, name: true, code: true } },
      assignedArtist: { select: { id: true, name: true, email: true, image: true } },
      _count: { select: { versions: true } },
      versions: {
        take: 1,
        orderBy: { versionNumber: "desc" },
        select: { id: true, versionNumber: true, approvalStatus: true, createdAt: true },
      },
    },
  });

  const artists = isArtist
    ? []
    : await db.user.findMany({
        where: { isActive: true },
        select: { id: true, name: true, email: true },
        orderBy: { name: "asc" },
      });

  // Counts for filter tabs
  const today = tasks.filter(
    (t) => t.dueDate && new Date(t.dueDate) >= todayStart && new Date(t.dueDate) < new Date(todayStart.getTime() + 86400000) && t.status !== "DONE"
  ).length;
  const overdue = tasks.filter(
    (t) => t.dueDate && new Date(t.dueDate) < todayStart && t.status !== "DONE"
  ).length;
  const inReview = tasks.filter((t) =>
    ["INTERNAL_REVIEW", "CLIENT_REVIEW"].includes(t.status)
  ).length;

  return (
    <TasksPageClient
      tasks={tasks as any}
      artists={artists}
      currentUserId={session.user.id}
      role={session.user.role}
      counts={{ today, overdue, inReview, total: tasks.length }}
      activeStatus={status}
      activeAssignee={assignee}
    />
  );
}
