"use client" // Error components must be Client Components

import { useParams, usePathname } from "next/navigation"
import { useEffect } from "react"
import { useIntl } from "react-intl"

import { login } from "@/constants/routes/handleAuth"
import { SESSION_EXPIRED } from "@/server/errors/trpc"

import { findLang } from "@/utils/languages"

import styles from "./error.module.css"

import { LangParams } from "@/types/params"

export default function Error({
  error,
}: {
  error: Error & { digest?: string }
}) {
  const intl = useIntl()
  const params = useParams<LangParams>()

  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error)

    if (error.message === SESSION_EXPIRED) {
      const loginUrl = login[params.lang]
      window.location.assign(loginUrl)
    }
  }, [error, params.lang])

  const pathname = usePathname()
  const lang = findLang(pathname)

  return (
    <section className={styles.layout}>
      <div className={styles.content}>
        {lang}: {intl.formatMessage({ id: "Something went wrong!" })}
      </div>
    </section>
  )
}
