import type { ClassProfile, ClassType, ClassTypeConfig } from '@renderer/types/app'

export const CLASSES_STORAGE_KEY = 'growth-report:student-classes'
const LEGACY_CLASSES_STORAGE_KEY = 'growth-report:classes'
export const DEFAULT_CLASS_TYPE_CONFIGS: ClassTypeConfig[] = [
  {
    id: 'cheap',
    label: '便宜班',
    courseContent:
      '本期开展了小袋鼠整合主题课程：(语言、社会、科学、健康、艺术）、生活数学；特色课程（英语、体能、美工、篮球）。'
  },
  {
    id: 'noble',
    label: '贵族班',
    courseContent:
      '本学期开展了柏克莱主题课程（语言、社会、科学、艺术、健康）；英语及特色课程（体能、舞蹈、美工、魔力猴、足球、国学）。'
  },
  {
    id: 'big',
    label: '大大班',
    courseContent:
      '本学期开展了双木桥主题课程（图说汉字、妙趣汉音、情智阅读、麦斯思维、专注力训练）；英语及特色课程（体能、舞蹈、美工、魔力猴、足球、国学）。'
  }
]
export const classTypeOptions: { value: ClassType; label: string }[] =
  DEFAULT_CLASS_TYPE_CONFIGS.map((config) => ({
    value: config.id,
    label: config.label
  }))

const defaultClassNames = ['云朵一班', '星星二班', '彩虹三班']

export function createUuid(): string {
  return crypto.randomUUID()
}

export function createDefaultClasses(): ClassProfile[] {
  return defaultClassNames.map((name) => ({
    id: createUuid(),
    name,
    type: 'cheap',
    teacherNames: []
  }))
}

export function normalizeClass(classItem: Partial<ClassProfile>): ClassProfile | null {
  if (!classItem.id || !classItem.name) {
    return null
  }

  return {
    id: classItem.id,
    name: classItem.name,
    type: classItem.type?.trim() || 'cheap',
    teacherNames: normalizeTeacherNames(classItem),
    familyPhoto: classItem.familyPhoto
  }
}

function normalizeTeacherNames(
  classItem: Partial<ClassProfile> & { teacherName?: string }
): string[] {
  if (Array.isArray(classItem.teacherNames)) {
    return classItem.teacherNames.map((teacherName) => teacherName.trim()).filter(Boolean)
  }

  return classItem.teacherName?.trim() ? [classItem.teacherName.trim()] : []
}

export function getClassTypeLabel(
  type: ClassType,
  configs: ClassTypeConfig[] = DEFAULT_CLASS_TYPE_CONFIGS
): string {
  return (configs.find((item) => item.id === type)?.label ?? type) || '便宜班'
}

export function loadClasses(): ClassProfile[] {
  const rawClasses =
    window.localStorage.getItem(CLASSES_STORAGE_KEY) ??
    window.localStorage.getItem(LEGACY_CLASSES_STORAGE_KEY)

  if (!rawClasses) {
    const classes = createDefaultClasses()
    saveClasses(classes)
    return classes
  }

  try {
    const classes = JSON.parse(rawClasses)
    if (Array.isArray(classes) && classes.length > 0) {
      const normalizedClasses = classes
        .map((classItem) => normalizeClass(classItem))
        .filter((classItem): classItem is ClassProfile => classItem !== null)

      if (normalizedClasses.length > 0) {
        saveClasses(normalizedClasses)
        return normalizedClasses
      }
    }

    const nextClasses = createDefaultClasses()
    saveClasses(nextClasses)
    return nextClasses
  } catch {
    const nextClasses = createDefaultClasses()
    saveClasses(nextClasses)
    return nextClasses
  }
}

export function loadLocalClassesForMigration(): ClassProfile[] {
  const rawClasses =
    window.localStorage.getItem(CLASSES_STORAGE_KEY) ??
    window.localStorage.getItem(LEGACY_CLASSES_STORAGE_KEY)

  if (!rawClasses) {
    return []
  }

  try {
    const classes = JSON.parse(rawClasses)
    return Array.isArray(classes)
      ? classes
          .map((classItem) => normalizeClass(classItem))
          .filter((classItem): classItem is ClassProfile => classItem !== null)
      : []
  } catch {
    return []
  }
}

export function clearLocalClassesForMigration(): void {
  window.localStorage.removeItem(CLASSES_STORAGE_KEY)
  window.localStorage.removeItem(LEGACY_CLASSES_STORAGE_KEY)
}

export function saveClasses(classes: ClassProfile[]): void {
  window.localStorage.setItem(CLASSES_STORAGE_KEY, JSON.stringify(classes))
}
