<script setup>
import TDataTable from "@/components/ui/TDataTable.vue";
import {onMounted, onUnmounted, ref} from "vue";

const emits = defineEmits(["sort"])
const props = defineProps(["items", "sortId"])

const onRowReorder = e => {
	if (e == null || !(e.value instanceof Array)) {
		return
	}

	let idField = "id"
	if (typeof props.sortId === "string" && props.sortId.length > 0) {
		idField = props.sortId
	}
	const ids = e.value.map(v => v[idField])
	emits("sort", ids)

	props.items.length = 0
	props.items.push(...e.value)
}

const rootRef = ref()
let container
const scrollListener = () => {
	updateColumnClass()
}

onMounted(() => {
	container = rootRef.value.$el.querySelector(".p-datatable-table-container")
	container.addEventListener("scroll", scrollListener)
	setTimeout(() => updateColumnClass())

	window.addEventListener("resize", scrollListener)
})

onUnmounted(() => {
	container.removeEventListener("scroll", scrollListener)
	window.removeEventListener("resize", scrollListener)
})

const updateColumnClass = () => {
	container.querySelectorAll(".p-datatable-frozen-column").forEach(columnEl => {
		columnEl.className = columnEl.className.replace(/(left|right)/, "").trim()
		const cssText = columnEl.style.cssText

		if (cssText.indexOf("left") >= 0) {
			if (container.scrollLeft > 0) {
				columnEl.className += " left"
			}
		} else {
			if (container.scrollWidth > container.offsetWidth && container.scrollLeft + container.offsetWidth < container.scrollWidth - 2) {
				columnEl.className += " right"
			}
		}
	})
}

</script>

<template>
	<TDataTable dataKey="id" :items="items" tableClass="ui table selectable" scrollable @row-reorder="onRowReorder" ref="rootRef">
		<slot></slot>
	</TDataTable>
</template>

<style lang="postcss" scoped>
:deep(.p-datatable-frozen-column.right) {
	box-shadow: -4px 0 8px -1px rgb(0 0 0 / 0.1);
	border-right: 1px solid rgba(34, 36, 38, 0.15) !important;

}

:deep(.p-datatable-frozen-column.left) {
	box-shadow: 4px 0 8px -1px rgb(0 0 0 / 0.1);
	border-left: 1px solid rgba(34, 36, 38, 0.15) !important;
	border-right: 1px solid rgba(34, 36, 38, 0.15) !important;
}

:deep(.p-datatable-table-container) {
	scrollbar-width: auto;
}

:deep(.p-datatable-tbody > tr > td) {
	border-color: inherit;
	border-bottom: 0;
}

:deep(tr:hover td) {
	@apply !bg-gray-50 dark:!bg-gray-700;
}

:deep(th.p-datatable-frozen-column.right), :deep(th.p-datatable-frozen-column.left) {
	background: var(--p-datatable-header-cell-background) !important;
}

</style>