import { isRouteErrorResponse } from 'react-router'
import { stripHtml } from 'string-strip-html'

import { getCategories } from '~/apis/common/get-categories'
import { getNews } from '~/apis/common/get-news'
import { getNewsBySlug } from '~/apis/common/get-news-by-slug'
import { getUser } from '~/apis/news/get-user'
import { APP } from '~/configs/meta'
import { handleCookie } from '~/libs/cookies'
import { NewsDetailPage } from '~/pages/news-detail'

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

export const loader = async ({ request, params }: Route.LoaderArgs) => {
  const userAgent = request.headers.get('user-agent')
  const ipAddress =
    request.headers.get('cf-connecting-ip') ||
    request.headers.get('x-forwarded-for') ||
    'localhost'
  const { userToken: accessToken } = await handleCookie(request)
  let userData
  if (accessToken) {
    const { data } = await getUser({ accessToken })
    userData = data
  }
  const { slug } = params
  let { data: newsDetailData } = await getNewsBySlug({
    slug,
    accessToken,
    userAgent,
    ipAddress,
  })
  const shouldSubscribe =
    (!accessToken || userData?.subscribe?.subscribe_plan?.code === 'basic') &&
    newsDetailData?.is_premium
  newsDetailData = {
    ...newsDetailData,
    content: shouldSubscribe
      ? stripHtml(newsDetailData.content).result.slice(0, 600)
      : newsDetailData.content,
  }
  const { data: categoriesData } = await getCategories()
  const beritaCode = 'berita'
  const beritaCategory = categoriesData.find(
    (category) => category.code === beritaCode,
  )
  const beritaData = getNews({ categories: [beritaCode], active: true })

  return {
    newsDetailData,
    beritaCategory,
    beritaData,
    shouldSubscribe,
  }
}

export const meta = ({ data }: Route.MetaArgs) => {
  const { newsDetailData } = data || {}
  const metaTitle = APP.title
  const title = `${newsDetailData?.title} - ${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 NewsDetailLayout = () => <NewsDetailPage />

export default NewsDetailLayout
