import { getTranslations, setRequestLocale } from 'next-intl/server'
import { Link } from '@/i18n/navigation'
import { searchTopics, countSearchTopics } from '@/lib/forum'
import { ForumSearchBox } from '@/components/ForumSearchBox'

export const dynamic = 'force-dynamic'

export default async function ForumSearchPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>
  searchParams: Promise<{ q?: string }>
}) {
  const { locale } = await params
  setRequestLocale(locale)
  const { q } = await searchParams
  const query = (q ?? '').trim()
  const t = await getTranslations('Forum')

  const valid = query.length >= 2
  const results = valid ? await searchTopics(query, 0, 30) : []
  const total = valid ? await countSearchTopics(query) : 0

  return (
    <main className="mx-auto max-w-4xl px-4 py-8">
      <p className="mb-2 text-sm">
        <Link href="/forum" className="text-sky-400 hover:underline">
          ← {t('backToForum')}
        </Link>
      </p>
      <h1 className="mb-6 text-2xl font-bold text-amber-500">{t('search')}</h1>
      <ForumSearchBox initial={query} />

      {!valid ? (
        <p className="text-amber-200/70">{t('searchHint')}</p>
      ) : results.length === 0 ? (
        <p className="text-amber-200/70">{t('noResults', { query })}</p>
      ) : (
        <>
          <p className="mb-4 text-sm text-amber-200/60">{t('resultsCount', { count: total, query })}</p>
          <ul className="divide-y divide-amber-900/40">
            {results.map((r) => (
              <li key={r.id} className="flex items-center justify-between gap-4 py-3">
                <div>
                  <Link href={`/forum/topic/${r.id}`} className="font-semibold text-amber-300 hover:text-amber-400">
                    {r.name}
                  </Link>
                  <p className="text-xs text-amber-200/60">
                    {t('in')}{' '}
                    <Link href={`/forum/${r.forum_id}`} className="text-sky-400 hover:underline">
                      {r.forum_name}
                    </Link>{' '}
                    · {t('by')} {r.poster}
                  </p>
                </div>
                {r.updated_at && (
                  <span className="whitespace-nowrap text-xs text-amber-200/50">
                    {new Date(r.updated_at).toLocaleDateString(locale)}
                  </span>
                )}
              </li>
            ))}
          </ul>
        </>
      )}
    </main>
  )
}
