import { notFound, redirect } from 'next/navigation'
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { getPost } from '@/lib/forum-write'
import { getTopic, getTopicPath } from '@/lib/forum'
import { getSession } from '@/lib/session'
import { forumIsModerator, canEditPost } from '@/lib/forum-perm'
import { PageShell } from '@/components/PageShell'
import { ForumBreadcrumb } from '@/components/ForumBreadcrumb'
import { EditPostPageForm } from '@/components/EditPostPageForm'

export const dynamic = 'force-dynamic'

export default async function EditPostPage({
  params,
}: {
  params: Promise<{ locale: string; postId: string }>
}) {
  const { locale, postId } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Forum')

  const id = Number(postId)
  const post = await getPost(id)
  if (!post) notFound()

  const session = await getSession()
  if (!session.username) redirect(`/${locale}/forum/topic/${post.topic}`)

  const isMod = await forumIsModerator(session)
  if (!canEditPost(session, isMod, post.poster)) redirect(`/${locale}/forum/topic/${post.topic}`)

  const topic = await getTopic(post.topic, true)
  const path = await getTopicPath(post.topic, locale)

  return (
    <PageShell title={t('editPost')}>
      <div className="main-wide">
        {path && (
          <ForumBreadcrumb
            items={[
              { label: t('title'), href: '/forum' },
              { label: path.forum, href: `/forum/${path.forum_id}` },
              { label: path.topic, href: `/forum/topic/${post.topic}` },
              { label: t('editPost') },
            ]}
          />
        )}
        <div className="forum_header create_header">
          <div className="forum_title">
            <h1>{topic?.name}</h1>
            {path && <h3>{path.forum}</h3>}
          </div>
        </div>
        <EditPostPageForm postId={id} topicId={post.topic} initialText={post.text} />
      </div>
    </PageShell>
  )
}
