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

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

import { AppSidebar } from '@/components/app-sidebar'
import { request as req } from '@/lib/request'

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'

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

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

  const sidebarState = await createCookie('sidebar_state').parse(rawCookie)
  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, sidebarState }
  }

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

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

export default function Route({ loaderData }: Route.ComponentProps) {
  const { user, orgs, sidebarState } = loaderData
  console.log(sidebarState)

  return (
    <SidebarProvider defaultOpen={sidebarState === 'true'} 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">
            <SidebarTrigger className="md:hidden" />
            <ThemedImage className="max-md:hidden" />

            <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>
  )
}
