import { redirect } from "next/navigation";
import { isAdminSession, getAllPermissions, hasPermission } from "@/lib/adminAuth";
import { getSessionClientId } from "@/lib/auth";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Order } from "@/models/Order";
import { AdminNavLinks } from "@/components/admin/AdminNavLinks";
import { AdminPageHeader } from "@/components/admin/AdminPageHeader";
import { TodoBoard } from "@/components/admin/TodoBoard";
import { getTodoList, getTodoTemplateList } from "@/lib/todoList";

export const dynamic = "force-dynamic";

export default async function AdminTodosPage() {
  if (!(await isAdminSession())) redirect("/de/login?next=%2Fde%2Fadmin%2Ftodos");

  const permissions = await getAllPermissions();
  const canViewAll = await hasPermission("todos_view");
  const canCreateForOthers = await hasPermission("todos_create");
  const canEditOthers = await hasPermission("todos_edit");
  const canDeleteOthers = await hasPermission("todos_delete");
  const viewerId = (await getSessionClientId()) || "";

  await connectDB();

  const [rawTodos, staff, recentOrders, templates] = await Promise.all([
    getTodoList(viewerId, canViewAll),
    Client.find({ role: "staff" }).select("name avatarPath").sort({ name: 1 }).lean(),
    Order.find({ archived: false, rejected: false }).select("characterOrConcept").sort({ createdAt: -1 }).limit(100).lean(),
    getTodoTemplateList(),
  ]);

  const staffList = staff.map((s) => ({ id: String(s._id), name: s.name, avatarPath: s.avatarPath || "" }));
  const orderOptions = recentOrders.map((o) => ({ id: String(o._id), label: o.characterOrConcept }));

  const todos = rawTodos.map((t) => ({
    id: t._id,
    title: t.title,
    description: t.description,
    assignedToId: t.assignedToId,
    additionalAssigneeIds: t.additionalAssigneeIds,
    watcherIds: t.watcherIds,
    createdById: t.createdById,
    status: t.status,
    priority: t.priority,
    dueDate: t.dueDate,
    orderId: t.orderId,
    labels: t.labels,
    project: t.project,
    subtasks: t.subtasks,
    attachments: t.attachments,
    activity: t.activity,
    notes: t.notes.map((n) => ({ id: n._id, authorId: n.authorId, text: n.text, createdAt: n.createdAt })),
    createdAt: t.createdAt,
    recurrence: t.recurrence,
    recurrenceInterval: t.recurrenceInterval,
    recurrenceWeekdays: t.recurrenceWeekdays,
    recurrenceEndDate: t.recurrenceEndDate,
  }));

  const allLabels = [...new Set(rawTodos.flatMap((t) => t.labels))].sort((a, b) => a.localeCompare(b));
  const allProjects = [...new Set(rawTodos.map((t) => t.project).filter(Boolean))].sort((a, b) => a.localeCompare(b));

  return (
    <main className="px-6 pt-4 pb-24 max-w-5xl mx-auto">
      <AdminNavLinks permissions={permissions} />
      <AdminPageHeader
        title="ToDos"
        subtitle={canViewAll ? "ToDos aller Mitarbeiter — deine eigenen siehst du immer, unabhängig von Filtern." : "Deine ToDos."}
      />
      <TodoBoard
        initialTodos={todos}
        staffList={staffList}
        orderOptions={orderOptions}
        templates={templates}
        allLabels={allLabels}
        allProjects={allProjects}
        viewerId={viewerId}
        canViewAll={canViewAll}
        canCreateForOthers={canCreateForOthers}
        canEditOthers={canEditOthers}
        canDeleteOthers={canDeleteOthers}
      />
    </main>
  );
}
