import { use } from "react"
import Link from "next/link"
import { getLocale } from "next-intl/server"
import {
  Activity,
  BookOpen,
  ClipboardList,
  FileText,
  LayoutDashboard,
  Library,
  Users,
  ChevronRight,
} from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { StatCard } from "@/shared/components/ui/stat-card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatDate } from "@/shared/lib/utils"
import type { AdminDashboardStreams } from "../../streams"
import { UserGrowthChart } from "./user-growth-chart"

type TranslationFunction = Awaited<ReturnType<typeof import("next-intl/server").getTranslations>>

// ─── 顶部统计栏 ────────────────────────────────────────────

export function AdminStatsBar({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const [usersStats, classesStats, homeworkStats] = use(Promise.all([
    streams.usersStats,
    streams.classesStats,
    streams.homeworkStats,
  ]))

  return (
    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
      <StatCard title={t("stats.users")} value={usersStats.userCount} icon={Users} color="text-blue-500" valueClassName="tabular-nums" href="/admin/users" />
      <StatCard title={t("stats.classes")} value={classesStats.classCount} icon={LayoutDashboard} color="text-emerald-500" valueClassName="tabular-nums" href="/admin/school/classes" />
      <StatCard title={t("stats.homeworkPublished")} value={homeworkStats.homeworkAssignmentPublishedCount} icon={ClipboardList} color="text-purple-500" valueClassName="tabular-nums" href="/admin/homework/assignments" />
      <StatCard title={t("stats.toGrade")} value={homeworkStats.homeworkSubmissionToGradeCount} icon={FileText} color="text-amber-500" valueClassName="tabular-nums" href="/admin/homework/submissions?status=submitted" />
    </div>
  )
}

// ─── 页头徽章（活跃会话 + 用户数） ─────────────────────────

export function AdminHeaderBadges({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const usersStats = use(streams.usersStats)

  return (
    <>
      <Badge variant="outline" className="gap-2">
        <Activity className="h-4 w-4" />
        {t("badge.activeSessions", { count: usersStats.activeSessionsCount })}
      </Badge>
      <Badge variant="outline" className="gap-2">
        <Users className="h-4 w-4" />
        {t("badge.users", { count: usersStats.userCount })}
      </Badge>
    </>
  )
}

// ─── 内容统计卡片 ──────────────────────────────────────────

export function AdminContentCard({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const [textbooksStats, questionsStats, examsStats] = use(Promise.all([
    streams.textbooksStats,
    streams.questionsStats,
    streams.examsStats,
  ]))

  return (
    <Card className="lg:col-span-1">
      <CardHeader>
        <CardTitle>{t("sections.content")}</CardTitle>
      </CardHeader>
      <CardContent className="grid gap-3">
        <ContentRow label={t("stats.textbooks")} value={textbooksStats.textbookCount} icon={<Library className="h-4 w-4 text-muted-foreground" />} href="/admin/textbooks" />
        <ContentRow label={t("stats.chapters")} value={textbooksStats.chapterCount} icon={<BookOpen className="h-4 w-4 text-muted-foreground" />} href="/admin/textbooks" />
        <ContentRow label={t("stats.questions")} value={questionsStats.questionCount} icon={<FileText className="h-4 w-4 text-muted-foreground" />} href="/admin/questions" />
        <ContentRow label={t("stats.exams")} value={examsStats.examCount} icon={<ClipboardList className="h-4 w-4 text-muted-foreground" />} href="/admin/exams" />
      </CardContent>
    </Card>
  )
}

// ─── 作业活跃度卡片 ────────────────────────────────────────

export function AdminHomeworkActivityCard({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const homeworkStats = use(streams.homeworkStats)

  return (
    <Card className="lg:col-span-1">
      <CardHeader>
        <CardTitle>{t("sections.homeworkActivity")}</CardTitle>
      </CardHeader>
      <CardContent className="grid gap-3">
        <ContentRow label={t("stats.totalAssignments")} value={homeworkStats.homeworkAssignmentCount} icon={<ClipboardList className="h-4 w-4 text-muted-foreground" />} href="/admin/homework/assignments" />
        <ContentRow label={t("stats.totalSubmissions")} value={homeworkStats.homeworkSubmissionCount} icon={<FileText className="h-4 w-4 text-muted-foreground" />} href="/admin/homework/submissions" />
        <ContentRow label={t("stats.toGrade")} value={homeworkStats.homeworkSubmissionToGradeCount} icon={<Activity className="h-4 w-4 text-muted-foreground" />} href="/admin/homework/submissions?status=submitted" />
      </CardContent>
    </Card>
  )
}

// ─── 用户角色分布卡片 ──────────────────────────────────────

export function AdminUserRolesCard({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const usersStats = use(streams.usersStats)

  return (
    <Card className="lg:col-span-1">
      <CardHeader>
        <CardTitle>{t("sections.userRoles")}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-3">
        {usersStats.userRoleCounts.length === 0 ? (
          <EmptyState title={t("empty.noUsers")} description={t("empty.noUsersDesc")} />
        ) : (
          usersStats.userRoleCounts.map((r) => (
            <div key={r.role} className="flex items-center justify-between">
              <Badge variant="secondary">{r.role}</Badge>
              <div className="text-sm font-medium tabular-nums">{r.count}</div>
            </div>
          ))
        )}
      </CardContent>
    </Card>
  )
}

// ─── 趋势图表 ──────────────────────────────────────────────

export function AdminTrendCharts({ t }: { t: TranslationFunction }) {
  // TODO(V4-P3-2): 趋势数据待接入真实统计查询（见 data-access.ts P2-4 TODO）
  // 当前 data-access.getAdminDashboardData 返回空数组，此处渲染空状态
  return (
    <div className="grid gap-6 lg:grid-cols-2">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("sections.userGrowthTrend")}</CardTitle>
        </CardHeader>
        <CardContent>
          <UserGrowthChart data={[]} labelKey="chart.newUsers" />
        </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("sections.homeworkSubmissionTrend")}</CardTitle>
        </CardHeader>
        <CardContent>
          <UserGrowthChart data={[]} labelKey="chart.newSubmissions" />
        </CardContent>
      </Card>
    </div>
  )
}

// ─── 最近注册用户表 ────────────────────────────────────────

export function AdminRecentUsersTable({ t, streams }: { t: TranslationFunction; streams: AdminDashboardStreams }) {
  const locale = use(getLocale())
  const usersStats = use(streams.usersStats)

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("sections.recentUsers")}</CardTitle>
      </CardHeader>
      <CardContent>
        {usersStats.recentUsers.length === 0 ? (
          <EmptyState title={t("empty.noUsersYet")} description={t("empty.seedHint")} />
        ) : (
          <Table>
            <caption className="sr-only">{t("sections.recentUsers")}</caption>
            <TableHeader>
              <TableRow>
                <TableHead>{t("table.name")}</TableHead>
                <TableHead>{t("table.email")}</TableHead>
                <TableHead>{t("table.role")}</TableHead>
                <TableHead>{t("table.created")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {usersStats.recentUsers.map((u) => (
                <TableRow key={u.id}>
                  <TableCell className="font-medium">{u.name || "-"}</TableCell>
                  <TableCell className="text-muted-foreground">{u.email}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{u.role ?? t("badge.unknown")}</Badge>
                  </TableCell>
                  <TableCell className="text-muted-foreground">{formatDate(u.createdAt, locale)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
        <div className="flex justify-end pt-4">
          <Button asChild variant="ghost" size="sm">
            <Link href="/admin/users">
              {t("sections.viewAllUsers")}
              <ChevronRight className="ml-1 h-4 w-4" />
            </Link>
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

// ─── 辅助组件 ──────────────────────────────────────────────

function ContentRow({
  label,
  value,
  icon,
  href,
}: {
  label: string
  value: number
  icon: React.ReactNode
  href?: string
}) {
  const content = (
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-2">
        {icon}
        <div className="text-sm text-muted-foreground">{label}</div>
      </div>
      <div className="text-sm font-medium tabular-nums">{value}</div>
    </div>
  )

  if (href) {
    return (
      <Link href={href} className="block rounded-md hover:bg-muted/50 transition-colors -mx-1 px-1 py-0.5">
        {content}
      </Link>
    )
  }

  return content
}
