import { requireDashboardContext } from "@/core/auth/dashboard-context";
import { buildTenantSubdomainUrl } from "@/core/config/domains";
import { getRequestHostname } from "@/core/tenant/request-tenant";
import { DashboardNavProvider } from "@/components/dashboard/nav-context";
import { DashboardSidebar } from "@/components/dashboard/sidebar";
import { DashboardTopBar } from "@/components/dashboard/top-bar";
import { countTenantInquiries } from "@/services/inquiry-service";
import { listDashboardJournal } from "@/services/journal-service";
import { listDashboardProjects } from "@/services/project-service";
import { getTenantSubscription } from "@/services/subscription-service";
import { listDashboardServices } from "@/services/studio-services-service";

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const ctx = await requireDashboardContext();
  const requestHost = await getRequestHostname();
  const siteUrl = buildTenantSubdomainUrl(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const [subscription, newInquiries, projects, services, journalPosts] =
    await Promise.all([
      getTenantSubscription(ctx.tenant.tenantId),
      countTenantInquiries(ctx.tenant, "new"),
      listDashboardProjects(ctx.tenant),
      listDashboardServices(ctx.tenant),
      listDashboardJournal(ctx.tenant),
    ]);

  const membership = ctx.principal.tenantMemberships.find(
    (m) => m.tenantId === ctx.tenant.tenantId && m.status === "active",
  );

  const trialEndsAt = subscription?.currentPeriodEnd
    ? subscription.currentPeriodEnd.toLocaleDateString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
      })
    : null;

  const draftProjects = projects.filter((p) => p.status === "draft").length;
  const draftJournal = journalPosts.filter((p) => p.status === "draft").length;

  return (
    <DashboardNavProvider>
      <div className="h-[100dvh] overflow-hidden bg-[var(--archi-cream-soft)]">
        <DashboardSidebar
          studioName={ctx.tenant.studioName}
          userName={ctx.user.name}
          userEmail={ctx.user.email}
          userRole={membership?.role ?? "member"}
          siteUrl={siteUrl}
          tenantSlug={ctx.tenant.tenantSlug}
          planName={subscription?.planName ?? null}
          planStatus={subscription?.status ?? null}
          trialEndsAt={
            subscription?.status === "trialing" ? trialEndsAt : null
          }
          newInquiryCount={newInquiries}
          draftProjectCount={draftProjects}
          draftJournalCount={draftJournal}
          unpublishedServiceCount={
            services.filter((s) => !s.isPublished).length
          }
        />
        <div className="flex h-full flex-col lg:pl-[260px]">
          <DashboardTopBar
            studioName={ctx.tenant.studioName}
            userName={ctx.user.name}
            userRole={membership?.role ?? "member"}
            siteUrl={siteUrl}
            tenantSlug={ctx.tenant.tenantSlug}
            newInquiryCount={newInquiries}
          />
          <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
            {children}
          </div>
        </div>
      </div>
    </DashboardNavProvider>
  );
}
