import { isRouteErrorResponse, Outlet, redirect } from 'react-router'
import { XiorError } from 'xior'

import { getStaff } from '~/apis/admin/get-staff'
import { AUTH_PAGES } from '~/configs/pages'
import { AdminDefaultLayout } from '~/layouts/admin/default'
import { handleCookie } from '~/libs/cookies'
import { setStaffLogoutHeaders } from '~/libs/logout-header.server'

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

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

  if (accessToken) {
    try {
      const { data } = await getStaff({ accessToken })
      staffData = data
    } catch (error) {
      if (error instanceof XiorError && error.response?.status === 401) {
        setStaffLogoutHeaders()
      }
    }
  }

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

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

  return {
    staffData,
  }
}

export const ErrorBoundary = ({ error }: Route.ErrorBoundaryProps) => {
  let message = 'Oops!'
  let details = 'An unexpected error occurred.'
  let stack: string | undefined

  if (isRouteErrorResponse(error)) {
    message = error.status === 404 ? '404' : 'Error'
    details =
      error.status === 404
        ? 'The requested page could not be found.'
        : error.statusText || details
  } else if (import.meta.env.DEV && error && error instanceof Error) {
    details = error.message
    stack = error.stack
  }

  return (
    <div className="container mx-auto p-4">
      <h1>{message}</h1>
      <p>{details}</p>
      {stack && (
        <pre className="w-full p-4 whitespace-pre-wrap">
          <code>{stack}</code>
        </pre>
      )}
    </div>
  )
}

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

export default AdminLayout
