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

export const CLASSES_STORAGE_KEY = 'growth-report:student-classes'
const LEGACY_CLASSES_STORAGE_KEY = 'growth-report:classes'
export const classTypeOptions: { value: ClassType; label: string }[] = [
  { value: 'cheap', label: '便宜班' },
  { value: 'noble', label: '贵族班' }
]

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

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

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

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 === 'noble' ? 'noble' : 'cheap',
    familyPhoto: classItem.familyPhoto
  }
}

export function getClassTypeLabel(type: ClassType): string {
  return classTypeOptions.find((item) => item.value === type)?.label ?? '便宜班'
}

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))
}
