import Link from "next/link";
import { headers } from "next/headers";
import { and, eq, isNull, sql } from "drizzle-orm";
import { requireCtx, listUserWorkspaces } from "@/lib/auth";
import { schema } from "@/db";
import { Shell } from "@/components/shell";
import { dict } from "@/lib/i18n";
import { brandingFor } from "@/lib/services/reports";
import { PLANS_CATALOG, lockedNav, normalizePlan, subscriptionAccess } from "@/lib/plans";

export const dynamic = "force-dynamic";

/** Pages that stay reachable when a trial or subscription has lapsed, so the customer can pay or fix their account. */
const ALWAYS_OPEN = ["/settings/billing", "/settings/security", "/settings/security-policy"];

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const ctx = await requireCtx();
  const db = ctx.db;
  const user = (await db.query.users.findFirst({ where: eq(schema.users.id, ctx.user!.id) }))!;
  const [workspaces, [unread], [inbox], [approvals], brand] = await Promise.all([
    listUserWorkspaces(db, user),
    db.select({ n: sql<number>`count(*)::int` }).from(schema.notifications).where(and(eq(schema.notifications.workspaceId, ctx.workspace.id), eq(schema.notifications.userId, user.id), isNull(schema.notifications.readAt))),
    db.select({ n: sql<number>`count(*)::int` }).from(schema.conversations).where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), eq(schema.conversations.status, "open"), ...(ctx.perms.messaging === "C:assigned" ? [eq(schema.conversations.assigneeId, user.id)] : []))),
    db.select({ n: sql<number>`count(*)::int` }).from(schema.aiActions).where(and(eq(schema.aiActions.workspaceId, ctx.workspace.id), eq(schema.aiActions.status, "proposed"))),
    brandingFor(ctx, true),
  ]);
  const locale = user.locale ?? ctx.workspace.locale;
  const path = (await headers()).get("x-pathname") ?? "";
  const access = subscriptionAccess(ctx.workspace);
  const plan = PLANS_CATALOG[normalizePlan(ctx.workspace.plan)];
  const blocked = !access.ok && !ALWAYS_OPEN.some((p) => path.startsWith(p));
  const isAdmin = ctx.perms.admin === "C";
  return (
    <Shell user={{ name: user.name, email: user.email, isAgencyAdmin: user.isAgencyAdmin }} workspace={{ id: ctx.workspace.id, name: ctx.workspace.name, plan: plan.name }}
      workspaces={workspaces.map((w) => ({ id: w.id, name: w.name }))} roleName={ctx.roleName} caps={Object.fromEntries(Object.entries(ctx.perms).filter(([, v]) => v))}
      strings={dict(locale)} locale={locale} unread={unread?.n ?? 0} inboxOpen={inbox?.n ?? 0} approvals={approvals?.n ?? 0}
      branding={{ productName: brand.name, color: brand.color, logoUrl: brand.logoUrl }} locked={lockedNav(ctx.workspace.plan)}>
      {access.ok && "trialDaysLeft" in access && (
        <div className="glass-panel mb-4 flex flex-wrap items-center gap-3 rounded-[18px] px-4 py-2.5 text-[13px]">
          <span className="rounded-full bg-brand/10 px-2.5 py-0.5 text-[12px] font-semibold text-brand">Free trial</span>
          <span><b>{access.trialDaysLeft} day{access.trialDaysLeft === 1 ? "" : "s"}</b> left on your {plan.name} trial.</span>
          {isAdmin && <Link href="/settings/billing" className="ml-auto rounded-full bg-ink px-3.5 py-1.5 text-[12px] font-semibold text-white dark:bg-white dark:text-ink">Choose a plan</Link>}
        </div>
      )}
      {access.ok && "pastDue" in access && <div className="mb-4 rounded-[18px] border border-warn/30 bg-warn/10 px-4 py-2.5 text-[13px] text-warn">Your last payment didn't go through. <Link href="/settings/billing" className="font-semibold underline">Update payment details</Link> to avoid interruption.</div>}
      {blocked ? (
        <div className="mx-auto mt-10 max-w-[560px]">
          <div className="glass-panel rounded-[28px] p-8 text-center">
            <div className="mx-auto grid h-14 w-14 place-items-center rounded-full bg-brand/10 text-[26px]">⏳</div>
            <h1 className="mt-4 text-[24px] font-extrabold tracking-tight">{!access.ok && access.reason === "trial_ended" ? "Your free trial has ended" : "Your subscription is inactive"}</h1>
            <p className="mt-2 text-[14px] text-ink-2">Your data is safe. {isAdmin ? "Choose a plan to pick up right where you left off." : "Ask your workspace admin to choose a plan to continue."}</p>
            {isAdmin && <Link href="/settings/billing" className="mt-6 inline-flex h-11 items-center rounded-[14px] bg-gradient-to-b from-[#3B76FF] to-brand-600 px-6 text-[14px] font-semibold text-white">See plans</Link>}
          </div>
        </div>
      ) : children}
    </Shell>
  );
}
