"use client";

import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { QuestionType } from "@/modules/questions/types";
import type {
  ActionState,
  LessonPlan,
  LessonPlanDocument,
  LessonPlanListItem,
  LessonPlanTemplate,
  LessonPlanVersion,
} from "../types";

// ---- V3 扩展：picker/dialog 组件所需的数据类型 ----

/** 教材选项（template-picker 使用）*/
export interface TextbookPickerOption {
  id: string;
  title: string;
  subject: string;
  grade: string | null;
}

/** 章节选项（template-picker 使用）
 * P1 修复：children 改为递归类型 ChapterPickerOption[]，消除 template-picker 中的 as 断言
 */
export interface ChapterPickerOption {
  id: string;
  title: string;
  parentId: string | null;
  order: number | null;
  content?: string | null;
  children?: ChapterPickerOption[];
}

/** 知识点选项（knowledge-point-picker 使用）*/
export interface KnowledgePointOption {
  id: string;
  name: string;
}

/** 发布作业输入（publish-homework-dialog 使用）*/
export interface PublishHomeworkInput {
  planId: string;
  blockId: string;
  classIds: string[];
  availableAt?: string;
  dueAt?: string;
}

/** 题库筛选参数（question-bank-picker 使用）*/
export interface QuestionPickerParams {
  q?: string;
  type?: QuestionType;
  difficulty?: number;
}

/** 题库题目项（question-bank-picker 使用）*/
export interface QuestionPickerItem {
  id: string;
  type: string;
  difficulty: number;
  content: unknown;
}

/**
 * 备课模块数据服务接口（P1-7 / V3 扩展）。
 * 抽象数据依赖，各角色/测试可提供不同实现，通过 LessonPlanProvider 注入。
 * 组件不直接 import actions，只通过此接口调用。
 */
export interface LessonPlanDataService {
  /** 查询课案列表 */
  getLessonPlans(params?: {
    query?: string;
    textbookId?: string;
    chapterId?: string;
    subjectId?: string;
    status?: string;
  }): Promise<{ success: boolean; data?: { items: LessonPlanListItem[] }; message?: string }>;

  /** 获取单个课案（V3 新增）*/
  getLessonPlanById(planId: string): Promise<{
    success: boolean;
    data?: { plan: LessonPlan };
    message?: string;
  }>;

  /** 更新课案内容（自动保存，V3 新增）*/
  updateLessonPlan(input: {
    planId: string;
    title?: string;
    content: LessonPlanDocument;
  }): Promise<{ success: boolean; message?: string }>;

  /** 保存版本（V3 新增）*/
  saveLessonPlanVersion(input: {
    planId: string;
    content: LessonPlanDocument;
    label?: string;
  }): Promise<{ success: boolean; data?: { versionNo: number }; message?: string }>;

  /** 获取课案版本列表 */
  getLessonPlanVersions(planId: string): Promise<{
    success: boolean;
    data?: { versions: LessonPlanVersion[] };
    message?: string;
  }>;

  /** 回退到指定版本 */
  revertLessonPlanVersion(params: {
    planId: string;
    versionNo: number;
  }): Promise<{ success: boolean; message?: string }>;

  /** 复制课案 */
  duplicateLessonPlan(planId: string): Promise<{ success: boolean; message?: string }>;

  /** 删除/归档课案 */
  deleteLessonPlan(planId: string): Promise<{ success: boolean; message?: string }>;

  /** 发布课案（V3 新增）*/
  publishLessonPlan(planId: string): Promise<{ success: boolean; message?: string }>;

  /** 撤回发布（V3 新增）*/
  unpublishLessonPlan(planId: string): Promise<{ success: boolean; message?: string }>;

  // ---- V3 新增：picker/dialog 组件所需方法 ----

  /** 创建课案（template-picker 使用）*/
  createLessonPlan(
    prevState: ActionState | null,
    formData: FormData,
  ): Promise<{ success: boolean; data?: { planId: string }; message?: string; errors?: Record<string, string[]> }>;

  /** 获取教材列表（template-picker 使用）*/
  getTextbooksForPicker(): Promise<{
    success: boolean;
    data?: { textbooks: TextbookPickerOption[] };
    message?: string;
  }>;

  /** 获取章节列表（template-picker 使用）*/
  getChaptersForPicker(textbookId: string): Promise<{
    success: boolean;
    data?: { chapters: ChapterPickerOption[] };
    message?: string;
  }>;

  /** 获取模板列表（template-picker 使用）*/
  getLessonPlanTemplates(): Promise<{
    success: boolean;
    data?: { templates: LessonPlanTemplate[] };
    message?: string;
  }>;

  /** 获取知识点选项（knowledge-point-picker 使用）*/
  getKnowledgePointOptions(input: {
    textbookId?: string;
    chapterId?: string;
  }): Promise<{
    success: boolean;
    data?: { options: KnowledgePointOption[] };
    message?: string;
    errors?: Record<string, string[]>;
  }>;

  /** 发布作业（publish-homework-dialog 使用）*/
  publishLessonPlanHomework(input: PublishHomeworkInput): Promise<{
    success: boolean;
    data?: { examId: string; assignmentId: string };
    message?: string;
    errors?: Record<string, string[]>;
  }>;

  // ---- V5-5：M6 附件库 UI 集成 ----

  /** 查询课案的所有附件（attachment-picker 使用）*/
  getLessonPlanAttachments(planId: string): Promise<{
    success: boolean;
    data?: { items: LessonPlanAttachmentOption[] };
    message?: string;
  }>;

  /** 创建附件记录（上传完成后调用，关联到课案）*/
  createLessonPlanAttachment(input: {
    planId: string;
    blockId?: string;
    fileId: string;
    displayName: string;
    attachmentType?: "reference" | "material" | "supplementary";
  }): Promise<{
    success: boolean;
    data?: { attachment: LessonPlanAttachmentOption | null };
    message?: string;
  }>;

  /** 删除附件 */
  deleteLessonPlanAttachment(attachmentId: string): Promise<{
    success: boolean;
    message?: string;
  }>;
}

/** V5-5：附件选项（供 picker 渲染）*/
export interface LessonPlanAttachmentOption {
  id: string;
  planId: string;
  blockId?: string;
  fileId: string;
  displayName: string;
  attachmentType: "reference" | "material" | "supplementary";
  uploadedBy: string;
  createdAt: string;
  /** V5-6 修复：MIME 类型，供 kindIcon 推断渲染方式 */
  mimeType?: string;
  /** V5-6 修复：渲染用 URL */
  url?: string;
}

/**
 * 跨模块题目服务接口（V4 P0-4 修复：完全解耦）。
 *
 * question-bank-picker 通过此接口调用题目查询，不直接 import questions 模块。
 * 由 LessonPlanProviderSetup 在 app 层注入具体实现（默认从 external-questions-bridge 取得）。
 */
export interface QuestionService {
  /** 获取题库题目（question-bank-picker 使用）*/
  getQuestions(params: QuestionPickerParams): Promise<{
    success: boolean;
    data?: { data: QuestionPickerItem[] };
    message?: string;
  }>;
}

/**
 * 角色配置（P1-7）：决定该模块渲染哪些 Widget/子模块/操作。
 * 新增角色只需新增配置项，不改组件代码。
 */
export interface LessonPlanRoleConfig {
  /** 是否显示"新建课案"按钮 */
  canCreate: boolean;
  /** 是否显示"编辑"入口 */
  canEdit: boolean;
  /** 是否显示"发布为作业" */
  canPublish: boolean;
  /** 是否显示"复制" */
  canDuplicate: boolean;
  /** 是否显示"归档/删除" */
  canArchive: boolean;
  /** 是否显示"版本历史" */
  canViewVersions: boolean;
  /** 是否显示"AI 知识点建议" */
  canUseAiSuggest: boolean;
  /** 是否只读模式（学生/家长查看 published 课案） */
  readOnly: boolean;
}

/** 默认教师配置 */
export const TEACHER_ROLE_CONFIG: LessonPlanRoleConfig = {
  canCreate: true,
  canEdit: true,
  canPublish: true,
  canDuplicate: true,
  canArchive: true,
  canViewVersions: true,
  canUseAiSuggest: true,
  readOnly: false,
};

/** 管理员配置（查看全校课案，不可编辑） */
export const ADMIN_ROLE_CONFIG: LessonPlanRoleConfig = {
  canCreate: false,
  canEdit: false,
  canPublish: false,
  canDuplicate: false,
  canArchive: false,
  canViewVersions: true,
  canUseAiSuggest: false,
  readOnly: true,
};

/** 学生配置（仅查看 published） */
export const STUDENT_ROLE_CONFIG: LessonPlanRoleConfig = {
  canCreate: false,
  canEdit: false,
  canPublish: false,
  canDuplicate: false,
  canArchive: false,
  canViewVersions: false,
  canUseAiSuggest: false,
  readOnly: true,
};

/** 家长配置（查看孩子的 published 课案） */
export const PARENT_ROLE_CONFIG: LessonPlanRoleConfig = {
  canCreate: false,
  canEdit: false,
  canPublish: false,
  canDuplicate: false,
  canArchive: false,
  canViewVersions: false,
  canUseAiSuggest: false,
  readOnly: true,
};

/** 教研组长/年级主任配置（V4 P1-11：查看所管年级的课案，只读 + 可看版本历史） */
export const GRADE_HEAD_ROLE_CONFIG: LessonPlanRoleConfig = {
  canCreate: false,
  canEdit: false,
  canPublish: false,
  canDuplicate: false,
  canArchive: false,
  canViewVersions: true,
  canUseAiSuggest: false,
  readOnly: true,
};

/** 角色配置注册表 */
export const ROLE_CONFIGS: Record<string, LessonPlanRoleConfig> = {
  admin: ADMIN_ROLE_CONFIG,
  teacher: TEACHER_ROLE_CONFIG,
  student: STUDENT_ROLE_CONFIG,
  parent: PARENT_ROLE_CONFIG,
  grade_head: GRADE_HEAD_ROLE_CONFIG,
  teaching_head: GRADE_HEAD_ROLE_CONFIG,
};

/** 监控埋点接口（P2-4）：预留关键操作埋点 */
export interface LessonPlanTracker {
  track(event: string, payload?: Record<string, unknown>): void;
}

/** 默认空实现埋点（生产环境可替换为真实埋点） */
export const noopTracker: LessonPlanTracker = {
  track: () => {},
};

/** 备课模块上下文值 */
export interface LessonPlanContextValue {
  /** 数据服务（抽象数据依赖） */
  service: LessonPlanDataService;
  /** 角色配置 */
  roleConfig: LessonPlanRoleConfig;
  /** 监控埋点 */
  tracker: LessonPlanTracker;
  /** 跨模块题目服务（V4 P0-4：可选，未注入时 question-bank-picker 回退禁用） */
  questionService?: QuestionService;
}

const LessonPlanContext = createContext<LessonPlanContextValue | null>(null);

/** Provider 组件：注入数据服务、角色配置、埋点、题目服务 */
export function LessonPlanProvider({
  children,
  service,
  roleConfig,
  tracker = noopTracker,
  questionService,
}: {
  children: ReactNode;
  service: LessonPlanDataService;
  roleConfig: LessonPlanRoleConfig;
  tracker?: LessonPlanTracker;
  questionService?: QuestionService;
}) {
  const value = useMemo<LessonPlanContextValue>(
    () => ({ service, roleConfig, tracker, questionService }),
    [service, roleConfig, tracker, questionService],
  );
  return <LessonPlanContext.Provider value={value}>{children}</LessonPlanContext.Provider>;
}

/** Hook：获取备课模块上下文值（若未在 Provider 内则返回 null，不抛错） */
export function useLessonPlanContextSafe(): LessonPlanContextValue | null {
  return useContext(LessonPlanContext);
}

/** Hook：获取备课模块上下文值（必须在 Provider 内使用） */
export function useLessonPlanContext(): LessonPlanContextValue {
  const ctx = useContext(LessonPlanContext);
  if (!ctx) {
    // V3 修复：开发者错误消息改为英文（非用户可见）
    throw new Error("useLessonPlanContext must be used within a LessonPlanProvider");
  }
  return ctx;
}

/** Hook：获取角色配置（若未在 Provider 内则返回教师默认配置） */
export function useRoleConfig(): LessonPlanRoleConfig {
  const ctx = useContext(LessonPlanContext);
  if (!ctx) {
    // V4 P1-12 修复：开发环境告警，避免误用导致非教师角色看到教师操作按钮
    if (process.env.NODE_ENV === "development") {
      console.warn(
        "[useRoleConfig] called outside LessonPlanProvider; falling back to TEACHER_ROLE_CONFIG. " +
          "Wrap the consuming component with <LessonPlanProviderSetup roleConfig={...}>.",
      )
    }
    return TEACHER_ROLE_CONFIG;
  }
  return ctx.roleConfig;
}

/** Hook：获取跨模块题目服务（V4 P0-4 修复） */
export function useQuestionService(): QuestionService | undefined {
  const ctx = useContext(LessonPlanContext);
  return ctx?.questionService;
}

/** Hook：获取数据服务 */
export function useLessonPlanService(): LessonPlanDataService {
  return useLessonPlanContext().service;
}

/** Hook：获取埋点 */
export function useLessonPlanTracker(): LessonPlanTracker {
  return useLessonPlanContext().tracker;
}

/** Hook：获取埋点（若未在 Provider 内则返回 noopTracker，不抛错） */
export function useLessonPlanTrackerSafe(): LessonPlanTracker {
  const ctx = useContext(LessonPlanContext);
  return ctx?.tracker ?? noopTracker;
}
