import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { use } from "react"
import { Users } from "lucide-react"

import { getParentDashboardAction } from "@/modules/dashboard/actions"
import { ParentDashboard } from "@/modules/parent/components/parent-dashboard"
import { ParentNoChildrenPage } from "@/modules/parent/components/parent-children-data-page"
import type { ActionState } from "@/shared/types/action-state"
import type { ParentDashboardData } from "@/modules/parent/types"

type ParentDashboardResult = ActionState<{
  data: ParentDashboardData | null
  hasChildren: boolean
}>

export const dynamic = "force-dynamic"

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

export default async function ParentDashboardPage(): Promise<JSX.Element> {
  // 传入未解析的 Promise，视图内用 React `use()` 消费，启用 Suspense 流式渲染
  const dataPromise = getParentDashboardAction()
  return <ParentDashboardResolver dataPromise={dataPromise} />
}

function ParentDashboardResolver({ dataPromise }: { dataPromise: Promise<ParentDashboardResult> }) {
  const result = use(dataPromise)
  if (!result.success || !result.data) {
    throw new Error(result.message ?? "Failed to load parent dashboard")
  }
  return <ParentDashboardBody data={result.data.data} hasChildren={result.data.hasChildren} />
}

async function ParentDashboardBody({
  data,
  hasChildren,
}: {
  data: ParentDashboardData | null
  hasChildren: boolean
}) {
  const t = await getTranslations("dashboard")

  if (!data || !hasChildren) {
    return (
      <div className="p-6 md:p-8">
        <ParentNoChildrenPage
          title={t("title.parent")}
          description={t("description.parent")}
          icon={Users}
          emptyTitle={t("empty.noChildren")}
          emptyDescription={t("empty.noChildrenDesc")}
        />
      </div>
    )
  }

  return (
    <div className="p-6 md:p-8">
      <ParentDashboard data={data} />
    </div>
  )
}
