<script lang="ts">
	import { onMount } from 'svelte';
	import { TrendingUp, TrendingDown, Minus } from 'lucide-svelte';
	import type { MetricWidgetConfig } from '$lib/types/widget.js';

	interface Props {
		config: MetricWidgetConfig;
	}

	let { config }: Props = $props();

	let currentValue: number | null = $state(null);
	let trend: 'up' | 'down' | 'flat' | null = $state(null);
	let loading = $state(true);
	let error = $state(false);

	const refreshMs = $derived((config.refreshInterval ?? 60) * 1000);

	function formatNumber(n: number): string {
		if (Math.abs(n) >= 1_000_000) {
			return (n / 1_000_000).toFixed(1) + 'M';
		}
		if (Math.abs(n) >= 1_000) {
			return (n / 1_000).toFixed(1) + 'K';
		}
		// Use locale formatting for smaller numbers
		return n.toLocaleString('en-US', { maximumFractionDigits: 2 });
	}

	async function fetchMetric() {
		error = false;
		try {
			 
			const params = new URLSearchParams({ source: config.source });
			if (config.value) params.set('value', config.value);
			if (config.url) params.set('url', config.url);
			if (config.jsonPath) params.set('jsonPath', config.jsonPath);
			if (config.query) params.set('query', config.query);

			const res = await fetch(`/api/widgets/metric?${params}`);
			if (res.ok) {
				const json = await res.json();
				if (json.success && json.data) {
					currentValue = json.data.value;
					trend = json.data.trend ?? null;
				}
			} else {
				error = true;
			}
		} catch {
			error = true;
		} finally {
			loading = false;
		}
	}

	onMount(() => {
		fetchMetric();
	});

	$effect(() => {
		const interval = setInterval(fetchMetric, refreshMs);
		return () => clearInterval(interval);
	});

	const trendColor = $derived.by(() => {
		if (trend === 'up') return 'var(--status-online-ink)';
		if (trend === 'down') return 'var(--status-offline-ink)';
		return 'var(--muted-foreground)';
	});
</script>

<div class="flex h-full flex-col items-center justify-center rounded-[1.4rem] border border-border bg-card shadow-[var(--shadow-soft)] p-4">
	{#if loading}
		<div class="flex flex-col items-center gap-2">
			<div class="h-10 w-24 animate-pulse rounded bg-muted"></div>
			<div class="h-4 w-16 animate-pulse rounded bg-muted"></div>
		</div>
	{:else if error}
		<span class="text-xs text-muted-foreground">Failed to load metric</span>
	{:else if currentValue !== null}
		<!-- Trend arrow -->
		<div class="mb-1" style="color: {trendColor};">
			{#if trend === 'up'}
				<TrendingUp class="h-5 w-5" />
			{:else if trend === 'down'}
				<TrendingDown class="h-5 w-5" />
			{:else}
				<Minus class="h-5 w-5" />
			{/if}
		</div>

		<!-- Big number -->
		<div class="flex items-baseline gap-1">
			<span class="font-display text-4xl font-semibold tabular-nums text-foreground">
				{formatNumber(currentValue)}
			</span>
			{#if config.unit}
				<span class="text-lg text-muted-foreground">{config.unit}</span>
			{/if}
		</div>

		<!-- Label -->
		<p class="mt-1 text-sm text-muted-foreground">{config.label}</p>
	{:else}
		<span class="text-xs text-muted-foreground">No data</span>
	{/if}
</div>
