<script lang="ts" setup>
import type { ColumnConfig } from './types'
import { CheckInput } from '@bagelink/vue'
import { formatCellValue } from './utils'

interface Props {
	col: ColumnConfig
	row: { [key: string]: any }
	rowIndex: number
	globalColIndex: number
	editing: boolean
	editable: boolean
	wrapText?: boolean
}

defineProps<Props>()

defineEmits<{
	(e: 'updateCell', rowIndex: number, key: string, value: string | boolean): void
	(e: 'stopEditing', cancelled: boolean): void
	(e: 'setInputRef', el: any, key: string): void
}>()
</script>

<template>
	<template v-if="editing">
		<input
			:ref="el => $emit('setInputRef', el, `cell-${rowIndex}-${globalColIndex}`)"
			:value="row[col.key]"
			type="text"
			class="spreadsheet-input"
			@input="(e) => $emit('updateCell', rowIndex, col.key, (e.target as HTMLInputElement).value)"
			@blur="$emit('stopEditing', false)"
			@keydown.enter.prevent="$emit('stopEditing', false)"
			@keydown.esc.prevent="$emit('stopEditing', true)"
			@mousedown.stop
		>
		<span class="spreadsheet-cell spreadsheetCellPlaceHolder">{{ formatCellValue(row[col.key], col.format) }}</span>
	</template>
	<template v-else-if="col.format === 'image'">
		<div class="h40px w-100p flex align-items-center justify-content-center overflow-hidden">
			<img class="w-100p h-100p contain radius-05" :src="row[col.key]" :alt="col.label || col.key">
		</div>
	</template>
	<template v-else-if="col.format === 'boolean'">
		<CheckInput
			:modelValue="!!row[col.key]"
			:disabled="!editable"
			@update:modelValue="(value) => $emit('updateCell', rowIndex, col.key, !!value)"
			@mousedown.stop
		/>
	</template>
	<template v-else>
		<span class="spreadsheet-cell">{{ formatCellValue(row[col.key], col.format) }}</span>
	</template>
</template>
