import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { Query } from "node-appwrite";

import { getActiveContext } from "@/lib/appwrite/active-context";
import { getLogoUrl } from "@/lib/appwrite/storage";
import { createAdminClient, createSessionClient, getCurrentUser } from "@/lib/appwrite/server";
import { DATABASE_ID, TABLES } from "@/lib/appwrite/schema";
import type { ThemePrefs } from "@/lib/appwrite/theme-prefs-actions";
import { PLAN_LIMITS } from "@/lib/plans";
import { DashboardShell } from "./dashboard-shell";

function detectMobileUA(ua: string | null): boolean {
  if (!ua) return false;
  return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(ua);
}

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const hdrs = await headers();
  const serverIsMobile = detectMobileUA(hdrs.get("user-agent"));

  const sessionUser = await getCurrentUser();
  if (!sessionUser) redirect("/sign-in");

  const ctx = await getActiveContext();
  if (!ctx) redirect("/onboarding");

  // Hard plan enforcement: non-owner members on free plan with more than 1 confirmed member
  const plan = ctx.settings?.plan ?? "free";
  const memberLimit = PLAN_LIMITS[plan].teamMembers;
  if (ctx.role !== "owner" && memberLimit !== Infinity && ctx.memberCount > memberLimit) {
    redirect("/plan-limit");
  }

  let pendingMatchCount = 0;
  try {
    const { tablesDB } = createAdminClient();
    const res = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.propertyMatches,
      queries: [Query.equal("tenantId", ctx.tenantId), Query.equal("notified", false), Query.limit(1)],
    });
    pendingMatchCount = res.total;
  } catch { /* non-critical */ }

  let themePrefs: ThemePrefs = {};
  try {
    const { account } = await createSessionClient();
    const raw = await account.getPrefs<ThemePrefs>();
    // getPrefs returns an Appwrite prototype object — serialize to plain object
    // so Next.js can pass it from Server → Client Component
    themePrefs = JSON.parse(JSON.stringify(raw)) as ThemePrefs;
  } catch {
    // use defaults if prefs unavailable
  }

  const company = {
    id: ctx.tenantId,
    name: ctx.settings?.officeName ?? "Çalışma alanı",
    logoUrl: getLogoUrl(ctx.settings?.logo) ?? null,
  };
  const user = {
    id: ctx.user.id,
    name: ctx.user.name || ctx.user.email,
    email: ctx.user.email,
  };

  return (
    <DashboardShell user={user} company={company} initialPrefs={themePrefs} pendingMatchCount={pendingMatchCount} role={ctx.role} serverIsMobile={serverIsMobile}>
      {children}
    </DashboardShell>
  );
}
