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

import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listServices } from "@/lib/appwrite/service-queries";
import { createAdminClient } from "@/lib/appwrite/server";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { ServicesClient } from "./components/services-client";

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

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

  const { teams } = createAdminClient();
  const [services, customers, membershipsResult] = await Promise.all([
    listServices(ctx.tenantId),
    listCustomers(ctx.tenantId),
    teams.listMemberships(ctx.tenantId).catch(() => ({ memberships: [] })),
  ]);

  const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
  const members = membershipsResult.memberships
    .filter((m) => m.confirm)
    .map((m) => ({ id: m.userId, name: m.userName || m.userEmail, email: m.userEmail }));

  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">Hizmetler</h1>
        <p className="text-muted-foreground text-sm">
          Müşterilere sunduğunuz hizmetleri ve fiyatlarını yönetin.
        </p>
      </div>

      <ServicesClient
        services={services.map((s) => ({
          id: s.$id,
          customerId: s.customerId,
          customerName: customerMap.get(s.customerId) ?? "—",
          name: s.name,
          description: s.description ?? "",
          unitPrice: s.unitPrice,
          currency: s.currency ?? "TRY",
          recurring: Boolean(s.recurring),
          billingPeriod: s.billingPeriod ?? "onetime",
          assigneeIds: s.assigneeIds ?? [],
          createdAt: s.$createdAt,
        }))}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
        members={members}
      />
    </div>
  );
}
