import type { Metadata } from "next";
import { redirect } from "next/navigation";

import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listTasks } from "@/lib/appwrite/task-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { createAdminClient } from "@/lib/appwrite/server";
import { TasksBoard } from "./components/tasks-board";
import type { TaskFilter } from "./components/types";

export const metadata: Metadata = {
  title: "İşletmem — Görevler",
};

const ALLOWED_FILTERS: TaskFilter[] = ["all", "mine", "unassigned", "mine_or_unassigned"];

export default async function TasksPage({
  searchParams,
}: {
  searchParams: Promise<{ view?: string }>;
}) {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const sp = await searchParams;
  const filter: TaskFilter =
    (ALLOWED_FILTERS as string[]).includes(sp.view ?? "")
      ? (sp.view as TaskFilter)
      : "mine_or_unassigned";

  const [allTasks, customers] = await Promise.all([
    listTasks(ctx.tenantId),
    listCustomers(ctx.tenantId),
  ]);

  const tasks = allTasks.filter((t) => {
    const assignee = t.assigneeId ?? "";
    if (filter === "mine") return assignee === ctx.user.id;
    if (filter === "unassigned") return !assignee;
    if (filter === "mine_or_unassigned")
      return !assignee || assignee === ctx.user.id;
    return true;
  });

  const filterCounts = {
    total: allTasks.length,
    mine: allTasks.filter((t) => t.assigneeId === ctx.user.id).length,
    unassigned: allTasks.filter((t) => !t.assigneeId).length,
    mineOrUnassigned: allTasks.filter(
      (t) => !t.assigneeId || t.assigneeId === ctx.user.id,
    ).length,
  };

  let teamMembers: { id: string; name: string }[] = [];
  try {
    const { teams } = createAdminClient();
    const memberships = await teams.listMemberships(ctx.tenantId);
    teamMembers = memberships.memberships.map((m) => ({
      id: m.userId,
      name: m.userName || m.userEmail,
    }));
  } catch {
    /* ignore */
  }

  const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
  const memberMap = new Map(teamMembers.map((m) => [m.id, m.name]));

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Görevler</h1>
        <p className="text-muted-foreground text-sm">
          Sürükle-bırak ile durumları değiştirin. Üstteki filtreden başkalarına atanmış
          görevleri de görebilirsiniz.
        </p>
      </div>

      <TasksBoard
        tasks={tasks.map((t) => ({
          id: t.$id,
          title: t.title,
          description: t.description ?? "",
          status: t.status ?? "todo",
          priority: t.priority ?? "medium",
          dueDate: t.dueDate ?? "",
          assigneeId: t.assigneeId ?? "",
          assigneeName: t.assigneeId ? memberMap.get(t.assigneeId) ?? "" : "",
          customerId: t.customerId ?? "",
          customerName: t.customerId ? customerMap.get(t.customerId) ?? "" : "",
          order: t.order ?? 0,
        }))}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
        teamMembers={teamMembers}
        currentUserId={ctx.user.id}
        filter={filter}
        filterCounts={filterCounts}
      />
    </div>
  );
}
