import { createFileRoute, Outlet, useRouterState } from '@tanstack/react-router';
import { Suspense } from 'react';
import { AppSidebar } from '@/components/sidebar/app-sidebar.view';
import { NavUserContainer } from '@/components/sidebar/nav-user.container';
import { NavUserSkeleton } from '@/components/sidebar/nav-user.skeletion';
import { SiteHeader } from '@/components/site-header';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import { navData } from '@/lib/navData';

export const Route = createFileRoute('/_workbenchLayout')({
  component: RouteComponent,
});

function RouteComponent() {
  const pathname = useRouterState({ select: state => state.location.pathname });
  const allNavItems = [...navData.navMain, ...navData.navSecondary];
  const title
    = allNavItems.find(item =>
      item.url === '/'
        ? pathname === '/'
        : pathname.startsWith(item.url),
    )?.title ?? '工作台';

  return (
    <SidebarProvider
      style={
        {
          '--sidebar-width': 'calc(var(--spacing) * 72)',
          '--header-height': 'calc(var(--spacing) * 12)',
        } as React.CSSProperties
      }
    >
      <AppSidebar
        navData={navData}
        footerWidget={(
          <Suspense fallback={<NavUserSkeleton />}>
            <NavUserContainer />
          </Suspense>
        )}
        variant="inset"
      />
      <SidebarInset>
        <SiteHeader title={title} />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <Outlet />
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  );
}
