"use client"

/**
 * exams 模块统一边界组件（P2-3）
 *
 * 设计目标：
 * - 复用 shared 层的 SectionErrorBoundary 与 EmptyState，避免每页重复实现
 * - 通过 next-intl 命名空间 "examHomework" 提供本地化文案
 * - 提供 ExamEmptyState / ExamSkeleton / ExamErrorBoundary 三个组合单元
 *
 * 使用示例：
 * ```tsx
 * <ExamErrorBoundary>
 *   <Suspense fallback={<ExamSkeleton variant="list" />}>
 *     {data.length === 0 ? <ExamEmptyState /> : <ExamGrid items={data} />}
 *   </Suspense>
 * </ExamErrorBoundary>
 * ```
 */

import type { ElementType, ErrorInfo, ReactNode } from "react"
import { useTranslations } from "next-intl"
import { FileText } from "lucide-react"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { cn } from "@/shared/lib/utils"

/**
 * 考试错误边界：薄包装 SectionErrorBoundary，固定使用 examHomework 命名空间。
 * 用于包裹任意考试相关数据区块，捕获渲染异常并显示统一的降级 UI。
 */
export function ExamErrorBoundary({
  children,
  fallback,
  onError,
}: {
  children: ReactNode
  fallback?: (error: Error, reset: () => void) => ReactNode
  onError?: (error: Error, info: ErrorInfo) => void
}): ReactNode {
  return (
    <SectionErrorBoundary namespace="examHomework" fallback={fallback} onError={onError}>
      {children}
    </SectionErrorBoundary>
  )
}

interface ExamEmptyStateProps {
  /** 空状态标题 i18n 键路径（相对 examHomework 命名空间），默认 "exam.list.empty" */
  titleKey?: string
  /** 空状态描述 i18n 键路径，默认 "exam.list.emptyDescription" */
  descriptionKey?: string
  /** 可选的引导操作（labelKey 为相对命名空间的 i18n 键） */
  action?: {
    labelKey: string
    onClick?: () => void
    href?: string
  }
  /** 自定义图标，默认 FileText */
  icon?: ElementType
  className?: string
}

/**
 * 考试空状态：默认显示"暂无考试"。
 * 标题/描述/操作均通过 i18n 键传入，调用方需保证对应翻译键存在。
 */
export function ExamEmptyState({
  titleKey = "exam.list.empty",
  descriptionKey = "exam.list.emptyDescription",
  action,
  icon = FileText,
  className,
}: ExamEmptyStateProps): ReactNode {
  const t = useTranslations("examHomework")
  const resolvedAction = action
    ? {
        label: t(action.labelKey),
        onClick: action.onClick,
        href: action.href,
      }
    : undefined
  return (
    <EmptyState
      icon={icon}
      title={t(titleKey)}
      description={t(descriptionKey)}
      action={resolvedAction}
      className={cn("border-none shadow-none h-auto", className)}
    />
  )
}

type ExamSkeletonVariant = "list" | "card" | "detail" | "analytics" | "editor"

interface ExamSkeletonProps {
  /** 骨架屏变体：list=列表页, card=卡片网格, detail=详情页, analytics=分析页, editor=富文本编辑器 */
  variant?: ExamSkeletonVariant
  className?: string
}

/**
 * 考试骨架屏：根据不同页面类型提供匹配的占位结构。
 */
export function ExamSkeleton({ variant = "list", className }: ExamSkeletonProps): ReactNode {
  const wrapperClass = cn("flex h-full flex-col space-y-8 p-8", className)
  if (variant === "card") {
    return (
      <div className={cn("grid grid-cols-1 gap-4 p-8 md:grid-cols-2 lg:grid-cols-3", className)}>
        {Array.from({ length: 6 }).map((_, idx) => (
          <div key={idx} className="space-y-3 rounded-lg border p-4">
            <Skeleton className="h-5 w-3/4" />
            <Skeleton className="h-4 w-1/2" />
            <div className="flex gap-2 pt-2">
              <Skeleton className="h-6 w-16" />
              <Skeleton className="h-6 w-16" />
              <Skeleton className="h-6 w-16" />
            </div>
            <Skeleton className="h-4 w-full" />
          </div>
        ))}
      </div>
    )
  }
  if (variant === "detail") {
    return (
      <div className={wrapperClass}>
        <Skeleton className="h-8 w-1/3" />
        <div className="space-y-4">
          <Skeleton className="h-20 w-full" />
          <Skeleton className="h-20 w-full" />
          <Skeleton className="h-20 w-full" />
        </div>
      </div>
    )
  }
  if (variant === "analytics") {
    return (
      <div className={wrapperClass}>
        <Skeleton className="h-7 w-40" />
        <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
          {Array.from({ length: 4 }).map((_, idx) => (
            <Skeleton key={idx} className="h-24 w-full rounded-lg" />
          ))}
        </div>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <Skeleton className="h-64 w-full rounded-lg" />
          <Skeleton className="h-64 w-full rounded-lg" />
        </div>
      </div>
    )
  }
  if (variant === "editor") {
    return (
      <div className={wrapperClass}>
        <Skeleton className="h-8 w-1/2" />
        <Skeleton className="h-10 w-full" />
        <div className="space-y-2 rounded-md border p-4">
          <Skeleton className="h-4 w-full" />
          <Skeleton className="h-4 w-[95%]" />
          <Skeleton className="h-4 w-[90%]" />
          <Skeleton className="h-4 w-[85%]" />
        </div>
      </div>
    )
  }
  // 默认 list 变体
  return (
    <div className={wrapperClass}>
      <div className="space-y-2">
        <Skeleton className="h-7 w-40" />
        <Skeleton className="h-4 w-72" />
      </div>
      <div className="space-y-3">
        <Skeleton className="h-10 w-full" />
        <div className="rounded-md border p-4">
          <div className="space-y-2">
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-[95%]" />
            <Skeleton className="h-4 w-[90%]" />
            <Skeleton className="h-4 w-[85%]" />
            <Skeleton className="h-4 w-[80%]" />
          </div>
        </div>
      </div>
    </div>
  )
}
