import { tv } from 'tailwind-variants'
import { mergeTailwindVariants } from '../utils/ux-merge-tailwind-variants'

export function useStyling(name: string, preset?: any, props?: any): ComputedRef<any> {
  const config = useAppConfig()

  return computed(() => {
    const overrides = (config.ux ?? {}) as Record<string, any>
    const merged = mergeTailwindVariants(preset ?? { slots: { base: '' } }, overrides[name])

    let generators: any = tv(merged)

    if (!Object.keys(generators.slots).length) {
      return { base: generators({ class: [props.ux?.base, props?.class] }) }
    }

    const variants: Record<string, string> = {}
    for (const variant in merged.variants ?? {}) {
      variants[variant] = props?.[variant] ?? merged.defaultVariants[variant]

      if (!(variant in variants)) {
        console.warn(`Value for variant ${variant} not specified in props or defaultVariants`)
      }
    }

    generators = generators(variants)
    const classes: Record<string, string> = {}

    for (const [slot, generator] of Object.entries(generators)) {
      if (generator == null) continue

      if (slot === 'base') {
        classes[slot] = generator({ class: [props.ux?.base, props?.class] }) ?? ''
      } else {
        classes[slot] = generator({ class: props.ux?.[slot] }) ?? ''
      }
    }

    return classes
  })
}
