"use client"

import { createContext, useContext, type ReactNode } from "react"

import type { ActionState } from "@/shared/types/action-state"
import type {
  TeacherDashboardData,
  StudentDashboardProps,
} from "@/modules/dashboard/types"
import type { TeacherDashboardMetrics } from "@/modules/dashboard/lib/dashboard-utils"
import type { ParentDashboardData } from "@/modules/parent/types"
import type { UsersDashboardStats } from "@/modules/users/data-access"
import type { ClassesDashboardStats } from "@/modules/classes/data-access"
import type { TextbooksDashboardStats } from "@/modules/textbooks/data-access"
import type { QuestionsDashboardStats } from "@/modules/questions/data-access"
import type { ExamsDashboardStats } from "@/modules/exams/data-access"
import type { HomeworkDashboardStats } from "@/modules/homework/stats-service"

// ─── 数据服务接口 ──────────────────────────────────────────

/**
 * 仪表盘数据服务接口（抽象数据依赖）。
 *
 * 每个角色提供独立的实现，封装对 data-access 的调用并加入权限校验。
 * 组件通过 `useDashboardService()` 获取当前注入的实现，不直接 import actions。
 * 测试时可注入 mock 实现以隔离数据层。
 */
export interface DashboardService {
  /** 获取管理员仪表盘数据（流式：返回未解析 Promise 供各分区独立消费） */
  getAdminStreams(): Promise<AdminDashboardStreams>
  /** 获取教师仪表盘数据 */
  getTeacherData(): Promise<ActionState<TeacherDashboardData & { metrics: TeacherDashboardMetrics }>>
  /** 获取学生仪表盘数据 */
  getStudentData(): Promise<ActionState<{
    student: { id: string; name: string } | null
    dashboardProps: Omit<StudentDashboardProps, "studentName"> | null
  }>>
  /** 获取家长仪表盘数据 */
  getParentData(): Promise<ActionState<{
    data: ParentDashboardData | null
    hasChildren: boolean
  }>>
}

/** 管理员仪表盘流式数据源（各分区独立 Promise） */
export interface AdminDashboardStreams {
  usersStats: Promise<UsersDashboardStats>
  classesStats: Promise<ClassesDashboardStats>
  textbooksStats: Promise<TextbooksDashboardStats>
  questionsStats: Promise<QuestionsDashboardStats>
  examsStats: Promise<ExamsDashboardStats>
  homeworkStats: Promise<HomeworkDashboardStats>
}

// ─── 监控埋点接口 ──────────────────────────────────────────

/**
 * 仪表盘监控埋点接口。
 *
 * 预留关键操作埋点，供后续接入实际监控 SDK（如 PostHog / Mixpanel）。
 * 默认实现为空操作，生产环境通过 Provider 注入实际实现。
 */
export interface DashboardAnalytics {
  /** Widget 被点击 */
  trackWidgetClick(widgetId: string, role: string): void
  /** 空状态被触发 */
  trackEmptyState(widgetId: string, role: string): void
  /** 错误重试 */
  trackErrorRetry(widgetId: string, role: string): void
  /** 页面停留 */
  trackPageView(role: string, durationMs: number): void
}

/** 空操作实现（默认） */
const noopAnalytics: DashboardAnalytics = {
  trackWidgetClick: () => {},
  trackEmptyState: () => {},
  trackErrorRetry: () => {},
  trackPageView: () => {},
}

// ─── React Context 依赖注入 ────────────────────────────────

const DashboardServiceContext = createContext<DashboardService | null>(null)
const DashboardAnalyticsContext = createContext<DashboardAnalytics>(noopAnalytics)

/** 仪表盘服务 Provider（在页面层注入角色特定的实现） */
export function DashboardServiceProvider({
  service,
  analytics,
  children,
}: {
  service: DashboardService
  analytics?: DashboardAnalytics
  children: ReactNode
}): ReactNode {
  return (
    <DashboardServiceContext.Provider value={service}>
      <DashboardAnalyticsContext.Provider value={analytics ?? noopAnalytics}>
        {children}
      </DashboardAnalyticsContext.Provider>
    </DashboardServiceContext.Provider>
  )
}

/** 获取当前注入的仪表盘数据服务 */
export function useDashboardService(): DashboardService {
  const service = useContext(DashboardServiceContext)
  if (!service) {
    throw new Error("useDashboardService must be used within DashboardServiceProvider")
  }
  return service
}

/** 获取当前注入的监控埋点接口 */
export function useDashboardAnalytics(): DashboardAnalytics {
  return useContext(DashboardAnalyticsContext)
}
