<script setup lang="ts" generic="T extends { [key: string]: any }, P extends Path<T>">
import type { Path, BaseBagelField } from '@bagelink/vue'
import type { Slots } from 'vue'
import type { TableSchemaProps } from '../types/TableSchema'
import { computed, useSlots } from 'vue'
import { useSchemaField } from '../composables/useSchemaField'
import { useTableData } from './dataTable/useTableData'

export interface DataPreviewProps<PT extends { [key: string]: any }> extends Omit<TableSchemaProps<PT>, 'data'> {
	modelValue: PT
	includeUnset?: boolean
}

export interface DataPreviewSlots<T, SP extends Path<T>> extends Slots {
	// [key: string]: VNodeFn<T, SP>
	[key: string]: (props: { row: T, field: BaseBagelField<T, SP> }) => any
}

const props = defineProps<DataPreviewProps<T>>()

const slots = useSlots() as DataPreviewSlots<T, P>

const data = computed(() => {
	// Handle undefined or null modelValue
	if (!props.modelValue) {
		return []
	}

	return Array.isArray(props.modelValue) ? props.modelValue : [props.modelValue]
})

const {
	computedSchema,
	computedData,
} = useTableData<T>({
	data,
	schema: props.schema,
	columns: props.columns,
	useServerSort: false
})

const firstItem = computed(() => {
	// Handle empty computedData
	if (!computedData.value || computedData.value.length === 0) {
		return {} as T
	}

	return computedData.value[0] || {} as T
})

const { renderField } = useSchemaField<T, P>({
	mode: 'preview',
	getFormData: () => firstItem.value,
	includeUnset: props.includeUnset,
	onUpdateModelValue: undefined,
})
</script>

<template>
	<div class="data-preview">
		<template v-if="computedSchema && computedSchema.length > 0">
			<template v-for="field in computedSchema" :key="field.id">
				<Component :is="renderField(field, slots as unknown as BaseBagelField<T, P>['slots'])" />
			</template>
		</template>
		<div v-else class="empty-preview">
			No data to display
		</div>
	</div>
</template>

<style scoped>
.data-preview {
	display: flex;
	flex-direction: column;
	gap: 0.5rem;
}

.preview-field {
	display: flex;
	flex-direction: row;
	align-items: center;
	gap: 0.5rem;
}

.field-label {
	font-size: 0.8rem;
	color: var(--bgl-black-tint);
	font-weight: 500;
}

.field-value {
	font-size: 0.95rem;
}

.empty-preview {
	font-size: 0.9rem;
	color: var(--bgl-black-tint);
	padding: 1rem 0;
	text-align: center;
}
</style>
