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

import { getAds } from '~/apis/common/get-ads'
import { getCategories } from '~/apis/common/get-categories'
import { getSubscribePlan } from '~/apis/common/get-subscribe-plan'
import { getUser } from '~/apis/news/get-user'
import { NewsProvider } from '~/contexts/news'
import { NewsDefaultLayout } from '~/layouts/news/default'
import { handleCookie } from '~/libs/cookies'
import { setUserLogoutHeaders } from '~/libs/logout-header.server'

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

export const loader = async ({ request }: Route.LoaderArgs) => {
  const { userToken: accessToken } = await handleCookie(request)
  let userData
  if (accessToken) {
    try {
      const { data } = await getUser({ accessToken })
      userData = data
    } catch (error) {
      if (error instanceof XiorError && error.response?.status === 401) {
        setUserLogoutHeaders()
      }
    }
  }
  const { data: subscribePlanData } = await getSubscribePlan()
  const { data: categoriesData } = await getCategories()
  let { data: adsData } = await getAds()
  if (adsData) {
    adsData = adsData?.filter(
      (ad) =>
        new Date(ad.start_date) <= new Date() &&
        new Date(ad.end_date) >= new Date(),
    )
  }

  return {
    userData,
    subscribePlanData,
    categoriesData,
    adsData,
  }
}

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 NewsLayout = () => {
  return (
    <NewsProvider>
      <NewsDefaultLayout>
        <Outlet />
      </NewsDefaultLayout>
    </NewsProvider>
  )
}

export default NewsLayout
