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

import { Outlet, type ShouldRevalidateFunctionArgs } from 'react-router'

import { AppSidebar } from '@/components/app-sidebar'
import { ModeToggle, ThemedImage } from '@/components/dark-mode'
import { NavUser } from '@/components/nav-user'
import { userContext } from '@/context'
import { useIsMobile } from '@/hooks/use-mobile'
import { request as req } from '@/lib/request'
import { authMiddleware } from '@/middleware/auth'
import {
  SidebarInset,
  SidebarProvider,
  SidebarTrigger
} from '@repo/ui/components/ui/sidebar'

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

export async function loader({ params, context, request }: Route.ActionArgs) {
  const user = context.get(userContext)

  const r = await req({
    url: `/users/${user.sub}/orgs?limit=25`,
    request,
    context
  })

  if (!r.ok) {
    throw new Response(await r.text(), { status: r.status })
  }

  const { items = [] } = (await r.json()) as { items: { sk: string }[] }
  const orgs = items.map(({ sk, ...props }) => ({
    ...props,
    id: sk?.split('#')[1] ?? null
  }))
  const exists = orgs.some(({ id }) => id === params.orgid)

  if (exists) {
    return { user, orgs }
  }

  throw new Response(null, { status: 401 })
}

export function shouldRevalidate({
  currentParams,
  nextParams
}: ShouldRevalidateFunctionArgs) {
  return currentParams.orgid !== nextParams.orgid
}

export default function Layout({ loaderData }: Route.ComponentProps) {
  const { user, orgs } = loaderData
  const isMobile = useIsMobile()

  return (
    <SidebarProvider className="flex">
      <AppSidebar orgs={orgs} />

      <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-5"
        >
          <div className="container mx-auto flex items-center">
            {isMobile ? <SidebarTrigger /> : <ThemedImage />}

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

        <main className="p-4">
          <div className="container mx-auto">
            <Outlet />
          </div>
        </main>
      </SidebarInset>
    </SidebarProvider>
  )
}
