import { Outlet, redirect } from 'react-router'

import { getStaff } from '~/apis/admin/get-staff'
import { getCategories } from '~/apis/common/get-categories'
import { getTags } from '~/apis/common/get-tags'
import { AUTH_PAGES } from '~/configs/pages'
import { AdminProvider } from '~/contexts/admin'
import { AdminDefaultLayout } from '~/layouts/admin/default'
import { handleCookie } from '~/libs/cookies'

import type { Route } from './+types/_admin.lg-admin'

export const loader = async ({ request }: Route.LoaderArgs) => {
  const { staffToken } = await handleCookie(request)
  const { pathname } = new URL(request.url)
  const isAuthPage = AUTH_PAGES.includes(pathname)
  let staffData

  if (!isAuthPage && !staffToken) {
    throw redirect('/lg-admin/login')
  }

  if (isAuthPage && staffToken) {
    throw redirect('/lg-admin')
  }

  if (staffToken) {
    const { data } = await getStaff({
      accessToken: staffToken,
    })
    staffData = data
  }
  const { data: categoriesData } = await getCategories()
  const { data: tagsData } = await getTags()

  return {
    staffData,
    categoriesData,
    tagsData,
  }
}

const AdminLayout = () => {
  return (
    <AdminProvider>
      <AdminDefaultLayout>
        <Outlet />
      </AdminDefaultLayout>
    </AdminProvider>
  )
}

export default AdminLayout
