import type { BglFormSchemaT, IfAny } from '@bagelink/vue'

import type { MaybeRefOrGetter, Ref, UnwrapRef } from 'vue'
import { getFallbackSchema } from '@bagelink/vue'
import { ref, toValue, watch } from 'vue'

export { useDevice } from './useDevice'
export { useExcel } from './useExcel'
export { usePolling } from './usePolling'
interface UseBglSchemaParamsT<T> {
	schema?: MaybeRefOrGetter<BglFormSchemaT<T>>
	columns?: MaybeRefOrGetter<string[]>
	data?: T[]
}

export function useBglSchema<T = { [key: string]: unknown }>(
	{ schema, columns, data }: UseBglSchemaParamsT<T> = {}
): BglFormSchemaT<T> {
	const _schema = $computed(() => toValue(schema))
	const _columns = $computed(() => toValue(columns))

	if (_schema) {
		return (
			_columns && _columns.length > 0
				? _schema.filter(f => _columns.includes(f.id as string))
				: _schema
		) as BglFormSchemaT<T>
	}
	return getFallbackSchema(data, _columns)
}

export function localRef<T>(
	key: string,
	initialValue: T
): [T] extends [Ref<any, any>] ?
		IfAny<T, Ref<T, T>, T> :
		Ref<UnwrapRef<T>, T | UnwrapRef<T>> {
	const storedValue = localStorage.getItem(key)
	const initial = storedValue !== null ? JSON.parse(storedValue) : initialValue
	const value = ref<T>(initial)

	watch(() => value.value, (val) => {
		localStorage.setItem(key, JSON.stringify(val))
	}, { immediate: true, deep: true })

	return value as any
}

export const useLocalStorage = localRef
export { useValidateFieldValue } from './useValidateFieldValue'
