"use client"

import { useState } from "react"

import type { AdminClassListItem } from "../types"
import { DEFAULT_CLASS_SUBJECTS } from "../types"
import type { SubjectTeacherState } from "../components/class-form-utils"

export interface UseClassDataReturn {
  createOpen: boolean
  setCreateOpen: (open: boolean) => void
  editItem: AdminClassListItem | null
  setEditItem: (item: AdminClassListItem | null) => void
  deleteItem: AdminClassListItem | null
  setDeleteItem: (item: AdminClassListItem | null) => void
  isWorking: boolean
  setIsWorking: (v: boolean) => void
  createTeacherId: string
  setCreateTeacherId: (id: string) => void
  createSchoolId: string
  setCreateSchoolId: (id: string) => void
  createGradeId: string
  setCreateGradeId: (id: string) => void
  editTeacherId: string
  setEditTeacherId: (id: string) => void
  editSchoolId: string
  setEditSchoolId: (id: string) => void
  editGradeId: string
  setEditGradeId: (id: string) => void
  editSubjectTeachers: SubjectTeacherState[]
  setSubjectTeacher: (subject: string, teacherId: string | null) => void
}

/**
 * 班级列表/弹窗共享状态：对话框开关、表单字段、提交中标记、重置逻辑。
 * - createOpen 打开时按默认值重置 create* 字段（使用 derived state 模式避免 useEffect）
 * - editItem 变化时按选中项重置 edit* 字段（使用 derived state 模式避免 useEffect）
 */
export function useClassData(config: {
  defaultTeacherId: string
  defaultSchoolId?: string
  defaultGradeId?: string
}): UseClassDataReturn {
  const { defaultTeacherId, defaultSchoolId = "", defaultGradeId = "" } = config
  const [isWorking, setIsWorking] = useState(false)
  const [createOpen, setCreateOpen] = useState(false)
  const [editItem, setEditItem] = useState<AdminClassListItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<AdminClassListItem | null>(null)
  const [createTeacherId, setCreateTeacherId] = useState(defaultTeacherId)
  const [createSchoolId, setCreateSchoolId] = useState(defaultSchoolId)
  const [createGradeId, setCreateGradeId] = useState(defaultGradeId)
  const [editTeacherId, setEditTeacherId] = useState("")
  const [editSchoolId, setEditSchoolId] = useState("")
  const [editGradeId, setEditGradeId] = useState("")
  const [editSubjectTeachers, setEditSubjectTeachers] = useState<SubjectTeacherState[]>([])

  // Derived state pattern: reset create form when dialog opens
  // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
  const [prevCreateOpen, setPrevCreateOpen] = useState(createOpen)
  if (createOpen !== prevCreateOpen) {
    setPrevCreateOpen(createOpen)
    if (createOpen) {
      setCreateTeacherId(defaultTeacherId)
      setCreateSchoolId(defaultSchoolId)
      setCreateGradeId(defaultGradeId)
    }
  }

  // Derived state pattern: reset edit form when editItem changes
  const [prevEditItem, setPrevEditItem] = useState(editItem)
  if (editItem !== prevEditItem) {
    setPrevEditItem(editItem)
    if (editItem) {
      setEditTeacherId(editItem.teacher.id)
      setEditSchoolId(editItem.schoolId ?? defaultSchoolId)
      setEditGradeId(editItem.gradeId ?? defaultGradeId)
      setEditSubjectTeachers(
        DEFAULT_CLASS_SUBJECTS.map((s) => ({
          subject: s,
          teacherId: editItem.subjectTeachers.find((st) => st.subject === s)?.teacher?.id ?? null,
        })),
      )
    }
  }

  const setSubjectTeacher = (subject: string, teacherId: string | null) => {
    setEditSubjectTeachers((prev) => prev.map((p) => (p.subject === subject ? { ...p, teacherId } : p)))
  }

  return {
    createOpen,
    setCreateOpen,
    editItem,
    setEditItem,
    deleteItem,
    setDeleteItem,
    isWorking,
    setIsWorking,
    createTeacherId,
    setCreateTeacherId,
    createSchoolId,
    setCreateSchoolId,
    createGradeId,
    setCreateGradeId,
    editTeacherId,
    setEditTeacherId,
    editSchoolId,
    setEditSchoolId,
    editGradeId,
    setEditGradeId,
    editSubjectTeachers,
    setSubjectTeacher,
  }
}
