import { isRouteErrorResponse } from 'react-router'

import { getCategories } from '~/apis/common/get-categories'
import { getNews } from '~/apis/common/get-news'
import { APP } from '~/configs/meta'
import { NewsCategoriesPage } from '~/pages/news-categories'

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

export const loader = async ({ params }: Route.LoaderArgs) => {
  const { data: categoriesData } = await getCategories()
  const { code } = params
  const categoryData = categoriesData.find((category) => category.code === code)
  const newsData = getNews({ categories: [code], active: true })
  return { categoryData, newsData }
}

export const meta = ({ data }: Route.MetaArgs) => {
  const { categoryData } = data
  const metaTitle = APP.title
  const title = `${categoryData?.name} - ${metaTitle}`

  return [
    {
      title,
    },
  ]
}

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 NewsCategoriesLayout = () => <NewsCategoriesPage />

export default NewsCategoriesLayout
