<script lang="ts" setup>
import type { ChartAxis, Data } from 'vue3-charts/dist/types'
import { onMounted, onUnmounted } from 'vue'
import {
	Area,
	Chart,
	Grid,
	Line,
	Marker,
	Tooltip,
} from 'vue3-charts'

const props = defineProps<{ data: Data[], locale: string }>()

const data = $computed(() => (props.locale === 'he' ? [...props.data].reverse() : props.data))

interface Size {
	width: number
	height: number
}

// Computed properties
const meanValue = $computed(() => {
	const sum = props.data.reduce((acc, curr) => acc + +curr.total_value, 0)
	return sum / props.data.length
})

const axisConfig = $computed<ChartAxis>(() => ({
	primary: {
		type: 'band',
		rotate: true,
		ticks: 5,
		domain: ['dataMin', 'dataMax'],
		tickValues:
			 props.data.length > 100 ? [''] : props.data.map((d: any) => d.date),
	},
	secondary: {
		domain: ['dataMin', 'dataMax * 1.05'],
		type: 'linear',
		ticks: 8,
	},
}))

// Constants
const BRAND_COLOR = 'var(--bgl-primary)'

const tooltipConfiguration = {
	date: { label: 'תאריך' },
	total_value: {
		color: BRAND_COLOR,
		label: 'סכום',
		format: (v: number) => `₪${v.toLocaleString() || ''}`,
	},
	total_count: {
		label: 'מספר התרומות',
		format: (v: number) => `${v.toLocaleString() || ''}`,
	},
}

// Refs
let chartSize = $ref<Size | undefined>()
const chartContainer = $ref<HTMLElement>()
const displayMarker = $ref(true)
const chartMargin = $ref({
	left: 0,
	top: 0,
	right: 0,
	bottom: 0,
})

// Functions
function adjustChartSize() {
	chartSize = undefined
	const el = chartContainer
	if (!el) return
	const { width, height } = el.getBoundingClientRect()
	chartSize = { width: width - 5, height: height - 10 }
	// console.log(chartSize)
}

function handleResize() {
	setTimeout(adjustChartSize, 300)
}

// Lifecycle hooks
onMounted(() => {
	adjustChartSize()
	window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
	window.removeEventListener('resize', handleResize)
})

// Style Configurations
function dotStyling(ctx: { [key: string]: any }) {
	return {
		r: ctx.active ? 5 : 1,
		fill: BRAND_COLOR,
	}
}
</script>

<template>
	<div
		ref="chartContainer"
		class="chart-line"
	>
		<Chart
			v-if="chartSize"
			:size="chartSize"
			:data
			:margin="chartMargin"
			:axis="axisConfig"
		>
			<template #layers>
				<Grid
					:center="true"
					strokeDasharray="2,2"
					:hideY="true"
				/>
				<Area
					aria-label="Profit/Loss"
					:dataKeys="['date', 'total_value']"
					type="monotone"
					:areaStyle="{ fill: 'url(#grad)' }"
				/>
				<Line
					:dataKeys="['date', 'total_value']"
					type="monotone"
					:dotStyle="dotStyling"
					:lineStyle="{ stroke: BRAND_COLOR, r: 2 }"
				/>
				<Marker
					v-if="displayMarker"
					:value="meanValue"
					label="ממוצע"
					:color="BRAND_COLOR"
					:strokeWidth="2"
					strokeDasharray="6 6"
				/>
				<defs>
					<linearGradient
						id="grad"
						gradientTransform="rotate(90)"
					>
						<stop
							offset="0%"
							:stop-color="BRAND_COLOR"
							stop-opacity="1"
						/>
						<stop
							offset="100%"
							stop-color="white"
							stop-opacity="0.4"
						/>
					</linearGradient>
				</defs>
			</template>
			<template #widgets>
				<Tooltip
					color="white"
					:config="tooltipConfiguration"
				/>
			</template>
		</Chart>
	</div>
</template>

<style>
.chart-line {
	width: 100%;
	height: 300px;
}

[dir="rtl"] .chart-line {
	direction: ltr;
}

.chart-line .v-tooltip-content>div {
	border: none !important;
	border-radius: 6px !important;
	background-color: black !important;
	opacity: 0.7;
	padding: 0.5rem 1rem !important;
	box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06) !important;
	font-weight: 300;
}

.chart-line .v-tooltip-content>div b {
	font-weight: 400;
}

.layer-grid g:last-child {
	display: none;
}

.layer-axis-x .tick:nth-child(2n + 1) {
	opacity: 0;
}

@media screen and (max-width: 910px) {
	.chart-line {
		height: 140px;
	}

	.layer-axis-x .tick {
		opacity: 0;
		font-size: 0;
	}
}
</style>
