import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { getRecipients, getMessageDrafts } from "@/modules/messaging/data-access"
import { MessageCompose } from "@/modules/messaging/components/message-compose"
import { MessageDraftList } from "@/modules/messaging/components/message-draft-list"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("messages")
  return {
    title: t("title.compose"),
    description: t("description.compose"),
  }
}

export default async function ComposeMessagePage({
  searchParams,
}: {
  searchParams: Promise<{ parentId?: string; receiverId?: string; subject?: string }>
}): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.MESSAGE_SEND)
  const sp = await searchParams
  const t = await getTranslations("messages")

  const [recipients, drafts] = await Promise.all([
    getRecipients(ctx.userId, ctx.dataScope),
    // P1-1: 获取草稿列表用于展示与恢复编辑
    getMessageDrafts(ctx.userId),
  ])

  return (
    <div className="flex h-full flex-col p-8">
      <div className="mx-auto w-full max-w-3xl space-y-6">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">{t("title.compose")}</h2>
          <p className="text-muted-foreground">{t("description.compose")}</p>
        </div>
        {/* P2-8: 撰写表单区块独立 ErrorBoundary，失败不影响草稿列表 */}
        <SectionErrorBoundary namespace="messages">
          <MessageCompose
            recipients={recipients}
            parentMessageId={sp.parentId}
            defaultReceiverId={sp.receiverId}
            defaultSubject={sp.subject}
          />
        </SectionErrorBoundary>
        {/* P2-8: 草稿列表区块独立 ErrorBoundary */}
        <SectionErrorBoundary namespace="messages">
          {/* P1-1: 草稿列表 - 允许用户查看、继续编辑、删除未发送的草稿 */}
          <MessageDraftList drafts={drafts} />
        </SectionErrorBoundary>
      </div>
    </div>
  )
}
