import type { Style } from '@dicebear/core'

type StyleDef = {
  id: string
  label: string
  loader: () => Promise<{ create: any; meta: any; schema: any }>
}

export const AVATAR_STYLE_LOADERS: StyleDef[] = [
  { id: 'bottts', label: 'Роботы', loader: () => import('@dicebear/bottts') },
  { id: 'identicon', label: 'Узоры', loader: () => import('@dicebear/identicon') },
  { id: 'avataaars', label: 'Персонажи', loader: () => import('@dicebear/avataaars') },
  { id: 'notionists', label: 'Notion', loader: () => import('@dicebear/notionists') },
  { id: 'thumbs', label: 'Thumbs', loader: () => import('@dicebear/thumbs') },
  { id: 'lorelei', label: 'Lorelei', loader: () => import('@dicebear/lorelei') },
  { id: 'micah', label: 'Micah', loader: () => import('@dicebear/micah') },
  { id: 'pixel-art', label: 'Пиксели', loader: () => import('@dicebear/pixel-art') },
  { id: 'rings', label: 'Кольца', loader: () => import('@dicebear/rings') },
  { id: 'shapes', label: 'Фигуры', loader: () => import('@dicebear/shapes') },
  { id: 'initials', label: 'Инициалы', loader: () => import('@dicebear/initials') },
  { id: 'adventurer', label: 'Adventurer', loader: () => import('@dicebear/adventurer') },
  { id: 'big-ears', label: 'Big Ears', loader: () => import('@dicebear/big-ears') },
  { id: 'big-smile', label: 'Big Smile', loader: () => import('@dicebear/big-smile') },
  { id: 'croodles', label: 'Croodles', loader: () => import('@dicebear/croodles') },
  { id: 'fun-emoji', label: 'Fun Emoji', loader: () => import('@dicebear/fun-emoji') },
]

export const DEFAULT_STYLE_ID = 'initials'

const styleCache = new Map<string, Style<any>>()

export async function loadAvatarStyle(id: string): Promise<Style<any>> {
  if (styleCache.has(id)) {
    return styleCache.get(id)!
  }

  const loader = AVATAR_STYLE_LOADERS.find((s) => s.id === id)
  if (!loader) {
    const fallback = AVATAR_STYLE_LOADERS.find((s) => s.id === DEFAULT_STYLE_ID)!
    const mod = await fallback.loader()
    const style = { create: mod.create, meta: mod.meta, schema: mod.schema }
    styleCache.set(DEFAULT_STYLE_ID, style)
    return style
  }

  const mod = await loader.loader()
  const style = { create: mod.create, meta: mod.meta, schema: mod.schema }
  styleCache.set(id, style)
  return style
}

export function getStyleLabel(id: string): string {
  return AVATAR_STYLE_LOADERS.find((s) => s.id === id)?.label ?? id
}
