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

import * as cookie from 'cookie'
import { Outlet, type ShouldRevalidateFunctionArgs } from 'react-router'
import { use, useEffect } from 'react'

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

import { WorkspaceProvider } from '@/components/workspace-switcher'
import { AppSidebar } from '@/components/app-sidebar'
import { workspaceMiddleware, workspaceContext } from '@/middleware/workspace'

// import { Notification } from '@/components/notification'

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

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

  const subscription = req({
    url: `/orgs/${activeWorkspace.id}/subscription`,
    request,
    context
  }).then((r) => r.json())

  const address = req({
    url: `/orgs/${activeWorkspace.id}/address`,
    request,
    context
  }).then((r) => r.json())

  return {
    user,
    activeWorkspace,
    workspaces,
    sidebar_state,
    subscription,
    address
  }
}

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

export default function Route({ loaderData }: Route.ComponentProps) {
  const {
    user,
    activeWorkspace,
    workspaces,
    sidebar_state,
    subscription: subscription_
  } = loaderData
  const subscription = use(subscription_)

  useEffect(() => {
    if (typeof window !== 'undefined' && window.rybbit) {
      window.rybbit.identify(user.sub, {
        username: user.email,
        name: user.name,
        email: user.email
      })
    }
  }, [])

  return (
    <WorkspaceProvider
      activeWorkspace={activeWorkspace}
      workspaces={workspaces}
      subscription={subscription}
    >
      <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"
          >
            <div className="container mx-auto flex items-center max-w-7xl">
              <SidebarTrigger className="md:hidden" />
              <ThemedImage className="max-md:hidden" />

              <div className="ml-auto flex gap-2.5 items-center">
                {/*<Notification />*/}
                <ModeToggle />
                <NavUser user={user} excludeApps={['admin']} />
              </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>
    </WorkspaceProvider>
  )
}
