import { notFound } from 'next/navigation'
import { getTranslations, setRequestLocale } from 'next-intl/server'
import {
  getTopic,
  getTopicPath,
  getPosts,
  countPosts,
  resolvePosters,
  getUserPostCount,
  getAccountCharactersForForum,
  getForumCharacterPick,
} from '@/lib/forum'
import { getPostsSocial, REPORT_REASONS } from '@/lib/forum-social'
import { formatForumDate } from '@/lib/forum-format'
import { localizeWowheadLinks } from '@/lib/forum-wowhead'
import { getSession } from '@/lib/session'
import { className, classColor } from '@/lib/wow-data'
import { forumIsModerator, canEditPost } from '@/lib/forum-perm'
import { PageShell } from '@/components/PageShell'
import { ForumBreadcrumb } from '@/components/ForumBreadcrumb'
import { Pagination } from '@/components/Pagination'
import { ReplyForm } from '@/components/ReplyForm'
import { ForumCharacterPicker } from '@/components/ForumCharacterPicker'
import { PostActions } from '@/components/PostActions'
import { EditPostForm } from '@/components/EditPostForm'
import { ForumModActions } from '@/components/ForumModActions'
import { WowheadRefresh } from '@/components/WowheadRefresh'

export const dynamic = 'force-dynamic'

const PER_PAGE = 5

export default async function TopicPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string; topicId: string }>
  searchParams: Promise<{ page?: string }>
}) {
  const { locale, topicId } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Forum')

  const id = Number(topicId)
  const session = await getSession()
  const isMod = await forumIsModerator(session)
  const topic = await getTopic(id, isMod)
  if (!topic) notFound()

  const total = await countPosts(id, isMod)
  const totalPages = Math.max(1, Math.ceil(total / PER_PAGE))
  const page = Math.min(Math.max(1, Number((await searchParams).page) || 1), totalPages)
  const rawPosts = await getPosts(id, (page - 1) * PER_PAGE, PER_PAGE, isMod)
  // Enlaces de wowhead en el idioma de QUIEN LEE (no de quien posteó).
  const posts = await Promise.all(
    rawPosts.map(async (p) => ({ ...p, text: await localizeWowheadLinks(p.text, locale) })),
  )

  const posters = await resolvePosters(posts.map((p) => p.poster))
  // Nº de posts por autor visible (para el panel lateral), en paralelo.
  const uniquePosters = [...new Set(posts.map((p) => p.poster))]
  const counts = new Map<number, number>(
    await Promise.all(uniquePosters.map(async (pid) => [pid, await getUserPostCount(pid)] as const)),
  )

  const social = await getPostsSocial(posts.map((p) => p.id), session.accountId ?? 0)
  const REASON_DESC: Record<string, string> = {
    troll: t('rTrollDesc'), threat: t('rThreatDesc'), username: t('rUsernameDesc'),
    offtopic: t('rOfftopicDesc'), inappropriate: t('rInappropriateDesc'), spam: t('rSpamDesc'),
    violence: t('rViolenceDesc'), child: t('rChildDesc'), illegal: t('rIllegalDesc'),
  }
  const REASON_LABEL: Record<string, string> = {
    troll: t('rTroll'), threat: t('rThreat'), username: t('rUsername'), offtopic: t('rOfftopic'),
    inappropriate: t('rInappropriate'), spam: t('rSpam'), violence: t('rViolence'),
    child: t('rChild'), illegal: t('rIllegal'),
  }
  const reportReasons = REPORT_REASONS.map((k) => ({ key: k, label: REASON_LABEL[k] || k, desc: REASON_DESC[k] || '' }))
  const paLabels = {
    like: t('like'), copyLink: t('copyLink'), copied: t('copied'), report: t('report'),
    bookmark: t('bookmark'), bookmarked: t('bookmarked'), loginRequired: t('loginToPost'),
    reportTitle: t('reportTitle'), reportIntro: t('reportIntro'), reportDetail: t('reportDetail'),
    reportSubmit: t('reportSubmit'), reportSent: t('reportSent'),
    reminderTitle: t('reminderTitle'), savedBookmark: t('savedBookmark'),
    remind2h: t('remind2h'), remindTomorrow: t('remindTomorrow'), remind3days: t('remind3days'), remindMore: t('remindMore'),
    editTitle: t('editBookmark'), notePlaceholder: t('notePlaceholder'), save: t('save'), cancel: t('cancel'),
    remove: t('removeBookmark'), reminderLabel: t('reminderLabel'), rNone: t('rNone'),
    rTomorrow: t('rmTomorrow'), rNextWeek: t('rmNextWeek'), rNextMonth: t('rmNextMonth'), rCustom: t('rmCustom'),
  }
  const paCanAct = Boolean(session.accountId)
  const paLoginHref = `/${locale}/my-account`

  const [forumChars, forumPick] = session.accountId
    ? await Promise.all([getAccountCharactersForForum(session.accountId), getForumCharacterPick(session.accountId)])
    : [[], null]

  const path = await getTopicPath(id, locale)
  const canReply = Boolean(session.username) && (!topic.locked || isMod)

  return (
    <PageShell
      title={
        <>
          {topic.sticky && `[${t('sticky')}] `}
          {topic.locked && `[${t('locked')}] `}
          {topic.deleted && `[${t('deleted')}] `}
          {topic.name}
        </>
      }
    >
      <div className="main-wide">
        <WowheadRefresh dep={`${id}-${page}`} />
        {path && (
          <ForumBreadcrumb
            items={[
              { label: t('title'), href: '/forum' },
              { label: path.forum, href: `/forum/${path.forum_id}` },
              { label: path.topic },
            ]}
          />
        )}

        <div className="topic_header">
          <div className="topic_title">
            <h1>{topic.name}</h1>
            <h3>{formatForumDate(topic.created, locale)}</h3>
          </div>
          <h4>
            <b>{total}</b> {t('posts')}
          </h4>
        </div>

        <div className="actions_c">
          <span />
          <Pagination page={page} totalPages={totalPages} hrefFor={(p) => `/forum/topic/${id}?page=${p}`} />
        </div>

        {posts.map((post) => {
          const author = posters.get(post.poster)
          const isStaff = author?.isStaff ?? false
          return (
            <div key={post.id} id={`post-${post.id}`} className={`topic_post${isStaff ? ' isStaff' : ''}${post.deleted ? ' post_deleted' : ''}`}>
              <div className="left_side">
                <div className="username_container">
                  <span className="username">
                    {author?.charName ?? author?.name ?? `#${post.poster}`}
                    {author?.guildName ? <span className="username_guild"> &lt;{author.guildName}&gt;</span> : null}
                  </span>
                </div>
                <div className={`user_avatar${isStaff ? ' isStaff' : ''}`}>
                  <span
                    style={{
                      background: `url(${author?.avatar ?? '/forum/avatars/class-1.gif'}) no-repeat center`,
                      backgroundSize: 'cover',
                    }}
                  />
                </div>
                <div className="user_info">
                  <h3 className="post_field">
                    <dt>
                      <i className="fa-solid fa-user-shield fa-fw" />
                    </dt>
                    <dd className={isStaff ? 'badge_staff' : undefined}>{isStaff ? t('staff') : t('member')}</dd>
                  </h3>
                  <h3 className="post_field">
                    <dt>
                      <i className="fa-solid fa-calendar fa-fw" />
                    </dt>
                    <dd>{formatForumDate(author?.joindate ?? null, locale) || '—'}</dd>
                  </h3>
                  {author?.charName ? (
                    <>
                      <h3 className="post_field">
                        <dt>
                          <i className="fa-solid fa-medal fa-fw" />
                        </dt>
                        <dd>{(author.achPoints ?? 0).toLocaleString(locale)}</dd>
                      </h3>
                      <h3 className="post_field">
                        <dt>
                          <i className="fa-solid fa-star fa-fw" />
                        </dt>
                        <dd>
                          {t('level')} {author.level}
                        </dd>
                      </h3>
                      <h3 className="post_field">
                        <dt>
                          <i className="fa-solid fa-khanda fa-fw" />
                        </dt>
                        <dd style={{ color: classColor(author.classId) }}>{className(author.classId, locale)}</dd>
                      </h3>
                    </>
                  ) : null}
                  <h3 className="post_field">
                    <dt>
                      <i className="fa-solid fa-comments fa-fw" />
                    </dt>
                    <dd>
                      {t('posts')}: {counts.get(post.poster) ?? 0}
                    </dd>
                  </h3>
                </div>
              </div>
              <div className="right_side">
                <div className="post_container" dangerouslySetInnerHTML={{ __html: post.text }} />
                <ul className="post_controls">
                  <li className="pa-li">
                    <PostActions
                      postId={post.id}
                      permalink={`/${locale}/forum/topic/${id}#post-${post.id}`}
                      canAct={paCanAct}
                      loginHref={paLoginHref}
                      initialLikes={social.get(post.id)?.likes ?? 0}
                      initialLiked={social.get(post.id)?.liked ?? false}
                      initialBookmarked={social.get(post.id)?.bookmarked ?? false}
                      initialNote={social.get(post.id)?.note ?? ''}
                      initialRemindAt={social.get(post.id)?.remindAt ?? null}
                      locale={locale}
                      reasons={reportReasons}
                      labels={paLabels}
                    />
                  </li>
                  <li className="post_date">{formatForumDate(post.time, locale)}</li>
                  {canEditPost(session, isMod, post.poster) && (
                    <li>
                      <EditPostForm postId={post.id} initialText={post.text} />
                    </li>
                  )}
                  {isMod && (
                    <li>
                      <ForumModActions kind="post" id={post.id} deleted={post.deleted} />
                    </li>
                  )}
                </ul>
              </div>
            </div>
          )
        })}

        <div className="actions_c">
          <span />
          <Pagination page={page} totalPages={totalPages} hrefFor={(p) => `/forum/topic/${id}?page=${p}`} />
        </div>

        {isMod && (
          <div className="forum-form-actions" style={{ marginBottom: 20 }}>
            <ForumModActions kind="topic" id={id} deleted={topic.deleted} locked={topic.locked} />
          </div>
        )}

        {canReply ? (
          page === totalPages ? (
            <>
              <ForumCharacterPicker
                locale={locale}
                initialChars={forumChars}
                initialCurrent={forumPick}
                labels={{
                  postingAs: t('postingAs'),
                  change: t('changeCharacter'),
                  title: t('changeCharacter'),
                  filter: t('filter'),
                  empty: t('noCharacters'),
                  auto: t('autoCharacter'),
                }}
              />
              <ReplyForm topicId={id} />
            </>
          ) : (
            <p className="forum-empty">
              <a href={`/forum/topic/${id}?page=${totalPages}`}>{t('replyOnLastPage')}</a>
            </p>
          )
        ) : (
          !session.username && <p className="forum-empty">{t('loginToPost')}</p>
        )}
      </div>
    </PageShell>
  )
}
