import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { Sidebar } from "@/components/sidebar/sidebar";
import { Breadcrumb } from "@/components/breadcrumb";
import { BottomToolbar } from "@/components/bottom-toolbar";
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger";
import type { DocumentRecord } from "@/lib/documents";
import { createSupabaseServerClient } from "@/lib/supabase/server";
import { ensureDefaultWorkspace, fetchWorkspaceSummaries } from "@/lib/workspaces";
import { fetchSidebarDataset } from "@/lib/sidebar-tree";
import type { SidebarInitialData } from "@/components/sidebar/types";
import { SearchPalette } from "@/components/search/search-palette";

export default async function AppLayout({ children }: { children: ReactNode }) {
  const supabase = await createSupabaseServerClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    redirect("/login");
  }

  await ensureDefaultWorkspace(supabase, session.user.id, session.user.email ?? "我的空间");
  const { workspaces, activeWorkspaceId } = await fetchWorkspaceSummaries(supabase, session.user.id);

  let documents: DocumentRecord[] = [];
  let sidebarInitialData: SidebarInitialData | null = null;

  if (activeWorkspaceId) {
    const dataset = await fetchSidebarDataset(supabase, activeWorkspaceId);     
    documents = dataset.documents;
    sidebarInitialData = {
      activeWorkspaceId,
      workspaces,
      documents: dataset.documents,
      trashedDocuments: dataset.trashedDocuments,
      mediaAssets: dataset.mediaAssets,
    };
  }

  return (
    <div className="flex h-screen bg-white">
      {sidebarInitialData && <Sidebar initialData={sidebarInitialData} />}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-10 items-center gap-4 border-b border-[#eeeeee] px-4">
          <MobileSidebarTrigger />
          <Breadcrumb documents={documents} />
        </header>
        <main className="flex-1 overflow-hidden bg-white">{children}</main>
        <BottomToolbar />
        <SearchPalette workspaceId={sidebarInitialData?.activeWorkspaceId ?? null} />
      </div>
    </div>
  );
}
