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/dashboard/components/parent-dashboard/parent-dashboard"
import { AiChildSummary } from "@/modules/ai/components/ai-child-summary"
import { ChildCard } from "@/modules/parent/components/child-card"
import { ParentAttentionBanner } from "@/modules/parent/components/parent-attention-banner"
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>
    )
  }

  const { parentName, children } = data

  // 组合注入：子女卡片列表（移动端水平滑动 + 桌面端网格）
  const childrenSlot = (
    <>
      <div
        className="flex gap-4 overflow-x-auto pb-2 snap-x snap-mandatory sm:hidden"
        aria-label={t("title.parent")}
      >
        {children.map((child) => (
          <div key={child.basicInfo.id} className="snap-start shrink-0 w-[85%]">
            <ChildCard child={child} />
          </div>
        ))}
      </div>
      <div className="hidden sm:grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {children.map((child) => (
          <ChildCard key={child.basicInfo.id} child={child} />
        ))}
      </div>
    </>
  )

  // AI 学情摘要区域：每个子女一张卡片
  // AiChildSummary 是客户端组件，由 AiClientProvider（dashboard layout 注入）提供数据服务
  // 仅传入已知安全字段（studentId / studentName / grade / homeworkCompletionRate），
  // recentGrades 字段因当前数据源不含 subject 信息暂不传，AI 仍可基于基本信息生成摘要
  const aiSummarySlot = (
    <div className="space-y-4 pt-2">
      <h2 className="text-lg font-semibold tracking-tight">{t("title.parent")}</h2>
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {children.map((child) => {
          const { pendingCount, submittedCount, gradedCount, overdueCount } = child.homeworkSummary
          const totalHomework = pendingCount + submittedCount + gradedCount + overdueCount
          const homeworkCompletionRate = totalHomework > 0
            ? (submittedCount + gradedCount) / totalHomework
            : undefined
          return (
            <AiChildSummary
              key={child.basicInfo.id}
              studentId={child.basicInfo.id}
              studentName={child.basicInfo.name ?? undefined}
              grade={child.basicInfo.gradeName ?? undefined}
              homeworkCompletionRate={homeworkCompletionRate}
            />
          )
        })}
      </div>
    </div>
  )

  return (
    <div className="p-6 md:p-8">
      <ParentDashboard
        parentName={parentName ?? ""}
        childrenCount={children.length}
        childrenSlot={childrenSlot}
        attentionBannerSlot={<ParentAttentionBanner data={data} />}
        aiSummarySlot={aiSummarySlot}
      />
    </div>
  )
}

