import { isRouteErrorResponse } from 'react-router'

import { getCategories } from '~/apis/common/get-categories'
import { getNews } from '~/apis/common/get-news'
import { Card } from '~/components/ui/card'
import { NewsPage } from '~/pages/news'

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

export const loader = async ({}: Route.LoaderArgs) => {
  const { data: categoriesData } = await getCategories()

  const spotlightCode = 'spotlight'
  const spotlightCategory = categoriesData.find(
    (category) => category.code === spotlightCode,
  )

  const beritaCode = 'berita'
  const beritaCategory = categoriesData.find(
    (category) => category.code === beritaCode,
  )

  const kajianCode = 'kajian'
  const kajianCategory = categoriesData.find(
    (category) => category.code === kajianCode,
  )

  const spotlightData = getNews({
    categories: [spotlightCode],
    active: true,
  })
  const beritaData = getNews({
    categories: [beritaCode],
    active: true,
  })
  const kajianData = getNews({
    categories: [kajianCode],
    active: true,
  })
  return {
    spotlightCategory,
    beritaCategory,
    kajianCategory,
    spotlightData,
    beritaData,
    kajianData,
  }
}

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 (
    <Card>
      <div className="mt-3 mb-3 grid items-center justify-between border-b border-black pb-3 sm:mb-[30px] sm:pb-[30px]">
        <h2 className="text-2xl font-extrabold text-[#2E2F7C] sm:text-4xl">
          {message}
        </h2>
        <p className="text-xl font-light text-[#777777] italic sm:text-2xl">
          {details}
        </p>
      </div>
      {stack && (
        <pre className="w-full whitespace-pre-wrap">
          <code>{stack}</code>
        </pre>
      )}
    </Card>
  )
}

const NewsIndexLayout = () => <NewsPage />

export default NewsIndexLayout
