<script setup lang="ts">
import { Card, Icon } from '@bagelink/vue'
import { computed } from 'vue'

interface Props {
	title: string
	value: number | string
	icon?: string
	color?: string
	percentageChange?: number
	prefix?: string
	suffix?: string
	currency?: Currency
	loading?: boolean
	subtitle?: string
}

type Currency = 'ILS' | 'USD' | 'EUR'

const props = withDefaults(defineProps<Props>(), {
	icon: 'trending_up',
	color: 'var(--bgl-primary)',
	percentageChange: 0,
	prefix: '',
	suffix: '',
	loading: false,
	subtitle: ''
})

const isIncreasing = computed(() => props.percentageChange >= 0)

const formattedValue = computed(() => {
	if (typeof props.value === 'string') { return props.value }

	if (props.currency) {
		return new Intl.NumberFormat('he-IL', {
			style: 'currency',
			currency: props.currency,
			minimumFractionDigits: 0
		}).format(props.value)
	}

	return props.value.toLocaleString()
})

const trendColor = computed(() => isIncreasing.value ? 'var(--bgl-green)' : 'var(--bgl-red)'
)
</script>

<template>
	<Card class=" flex column space-between align-items-start py-1 px-1-5 m_p-1 relative ">
		<div class="mb-1 flex space-between align-items-start m_mb-05 w-100p">
			<div class="flex gap-025">
				<Icon :name="icon" size="1" :color="color" class="line-height-0" weight="300" />
				<div>
					<h3 class="txt14 m-0 line-height-12 light opacity-6">
						{{ title }}
					</h3>
					<p v-if="subtitle" class="txt12 color-gray">
						{{ subtitle }}
					</p>
				</div>
			</div>
			<div v-if="percentageChange !== 0" class="kpi-trend flex gap-025 txt12 bold ms-auto" :style="{ color: trendColor }">
				<Icon :name="isIncreasing ? 'trending_up' : 'trending_down'" />
				<span>{{ Math.abs(percentageChange).toFixed(1) }}%</span>
			</div>
		</div>

		<div class="flex">
			<div class="flex align-items-baseline gap-025 w100p" :class="{ loading }">
				<span v-if="prefix" class="kpi-prefix txt16 semi color-gray">{{ prefix }}</span>
				<span class="kpi-main-value bold txt28 m_txt24 line-height-1">{{ loading ? '...' : formattedValue }}</span>
				<span v-if="suffix" class="kpi-suffix txt16 semi color-gray">{{ suffix }}</span>
			</div>
		</div>
	</Card>
</template>

<style scoped>
.loading .kpi-main-value {
	color: var(--bgl-gray);
}
</style>
