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

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

	// Add a dummy header item to account for thead height
	const dataWithHeader = computed(() => {
		const originalData = toValue(options.data)
		return [{ __isHeader: true } as any, ...originalData]
	})

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

	// Filter out the dummy header from the list
	const filteredList = computed(() => {
		return list.value.filter(item => !item.data.__isHeader)
	})

	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: filteredList,
		containerProps,
		wrapperProps,
		scrollTo,
		lastItemEl,
		registerLastItemObserver
	}
}
