import type { Route } from './+types/route'

import * as cookie from 'cookie'
import { Outlet } from 'react-router'

import { userContext } from '@repo/auth/context'
import { authMiddleware } from '@repo/auth/middleware/auth'
import { ModeToggle, ThemedImage } from '@repo/ui/components/dark-mode'
import { NavUser } from '@repo/ui/components/nav-user'
import {
  SidebarInset,
  SidebarProvider,
  SidebarTrigger
} from '@repo/ui/components/ui/sidebar'
import { Toaster } from '@repo/ui/components/ui/sonner'

import { AppSidebar } from '@/components/app-sidebar'

export const middleware: Route.MiddlewareFunction[] = [authMiddleware]

export async function loader({ context, request }: Route.ActionArgs) {
  const user = context.get(userContext)
  const rawCookie = request.headers.get('cookie') || ''
  const parsedCookies = cookie.parse(rawCookie)
  const { sidebar_state = 'true' } = parsedCookies

  return Response.json({ user, sidebar_state })
}

export default function Route({ loaderData }: Route.ComponentProps) {
  const { user, sidebar_state } = loaderData

  return (
    <SidebarProvider defaultOpen={sidebar_state === 'true'} className="flex">
      <AppSidebar />

      <SidebarInset className="relative flex flex-col flex-1 min-w-0">
        <header
          className="bg-background/15 backdrop-blur-sm
                     px-4 py-2 lg:py-4 sticky top-0 z-10
                     md:rounded-t-2xl"
        >
          <div className="container mx-auto flex items-center max-w-7xl">
            <SidebarTrigger className="md:hidden" />
            <ThemedImage className="max-md:hidden flex gap-1">
              <span className="text-muted-foreground text-xs">Insights</span>
            </ThemedImage>

            <div className="ml-auto flex gap-2.5 items-center">
              <ModeToggle />
              <NavUser user={user} />
            </div>
          </div>
        </header>

        <div className="p-4">
          <div className="container mx-auto relative max-w-7xl">
            <Outlet />
            <Toaster
              position="top-center"
              richColors={true}
              duration={Infinity}
              closeButton={true}
            />
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}
