import type { TableVirtualizationOptions } from '../../types/TableSchema'
import { useVirtualList, useIntersectionObserver, until } from '@vueuse/core'
import { ref, toValue } from 'vue'

export function useTableVirtualization<T>(options: TableVirtualizationOptions<T>) {
	const lastItemEl = ref<HTMLTableRowElement | null>(null)

	// For useVirtualList, which expects MaybeRef
	const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(
		options.data,
		{
			itemHeight: options.itemHeight,
			overscan: 10,
		}
	)

	async function registerLastItemObserver() {
		await until(() => lastItemEl.value).toBeTruthy()

		useIntersectionObserver(lastItemEl, ([entry]) => {
			// Check if options.data.value exists and has length
			const dataLength = toValue(options.data).length || 0

			if (entry.isIntersecting && dataLength > 0) {
				options.onLastItemVisible?.()
			}
		})
	}

	return {
		list,
		containerProps,
		wrapperProps,
		scrollTo,
		lastItemEl,
		registerLastItemObserver
	}
}
