import { isRouteErrorResponse } from 'react-router'

import { getCategories } from '~/apis/common/get-categories'
import { getNews } from '~/apis/common/get-news'
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,
  )

  return {
    spotlightCategory,
    spotlightCode,
    beritaCategory,
    beritaCode,
    kajianCategory,
    kajianCode,
  }
}

export const clientLoader = async ({
  serverLoader,
}: Route.ClientLoaderArgs) => {
  const serverData = await serverLoader()

  let { data: spotlightNews } = await getNews({
    categories: [serverData.spotlightCode],
  })
  spotlightNews = spotlightNews.filter(
    (news) => new Date(news.live_at) <= new Date(),
  )
  let { data: beritaNews } = await getNews({
    categories: [serverData.beritaCode],
  })
  beritaNews = beritaNews.filter((news) => new Date(news.live_at) <= new Date())
  let { data: kajianNews } = await getNews({
    categories: [serverData.kajianCode],
  })
  kajianNews = kajianNews.filter((news) => new Date(news.live_at) <= new Date())

  return {
    ...serverData,
    spotlightNews,
    beritaNews,
    kajianNews,
  }
}

clientLoader.hydrate = true as const

export const HydrateFallback = () => {
  return <div>Loading...</div>
}

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 NewsIndexLayout = () => <NewsPage />

export default NewsIndexLayout
