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

import { listCalendarEvents } from "@/lib/appwrite/calendar-queries";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listTasks } from "@/lib/appwrite/task-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { CalendarClient } from "./components/calendar-client";

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

export default async function CalendarPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

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

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

  const mappedEvents = events.map((e) => ({
    id: e.$id,
    title: e.title,
    description: e.description ?? "",
    start: e.start,
    end: e.end,
    allDay: Boolean(e.allDay),
    customerId: e.customerId ?? "",
    customerName: e.customerId ? customerMap.get(e.customerId) ?? "" : "",
    color: e.color ?? "",
    source: "event" as const,
  }));

  const mappedTasks = tasks
    .filter((t) => t.dueDate && t.status !== "done")
    .map((t) => ({
      id: t.$id,
      title: t.title,
      description: t.description ?? "",
      start: t.dueDate!,
      end: t.dueDate!,
      allDay: true,
      customerId: "",
      customerName: "",
      color: "task",
      source: "task" as const,
      taskStatus: t.status,
    }));

  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">Takvim</h1>
        <p className="text-muted-foreground text-sm">
          Toplantılar, randevular ve önemli tarihler.
        </p>
      </div>

      <CalendarClient
        events={[...mappedEvents, ...mappedTasks]}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
      />
    </div>
  );
}
