<script lang="ts">
	import * as Card from '$lib/components/ui/card';
	import { Badge } from '$lib/components/ui/badge';
	import type { ActivityItem } from '$lib/api/dashboard/types';
	import {
		FileText,
		Users,
		Package,
		CheckCircle,
		Clock,
		AlertCircle,
		TruckIcon
	} from 'lucide-svelte';
	import { m } from '$lib/i18n/messages';
	import { getLocale } from '$lib/paraglide/runtime';

	interface Props {
		activities: ActivityItem[];
		class?: string;
	}

	let { activities, class: cls = '' }: Props = $props();

	const icons = {
		invoice: FileText,
		pedimento: FileText,
		client: Users,
		provider: Users,
		item: Package,
		transport: TruckIcon
	};

	const statusColors = {
		active: 'default',
		pending: 'secondary',
		completed: 'outline',
		error: 'destructive'
	} as const;

	function getIcon(type: string) {
		return icons[type as keyof typeof icons] || FileText;
	}

	function formatDate(dateStr: string): string {
		// Normalizar: si el string no tiene info de zona horaria, asumir UTC agregando 'Z'
		const normalized = /[Z+\-]\d*$/.test(dateStr.trim()) ? dateStr : dateStr + 'Z';
		const date = new Date(normalized);
		const now = new Date();
		const diffMs = now.getTime() - date.getTime();

		// Si la fecha es futura (diff negativo) o muy reciente, mostrar 'Ahora mismo'
		if (diffMs < 0) {
			return m.dashboard_just_now();
		}

		const diffMins = Math.floor(diffMs / 60000);
		const diffHours = Math.floor(diffMs / 3600000);
		const diffDays = Math.floor(diffMs / 86400000);

		if (diffMins < 1) {
			return m.dashboard_just_now();
		} else if (diffMins < 60) {
			return `${m.dashboard_ago_suffix()} ${diffMins} ${m.dashboard_min_short()}`;
		} else if (diffHours < 24) {
			return `${m.dashboard_ago_suffix()} ${diffHours}${m.dashboard_h_short()}`;
		} else if (diffDays < 7) {
			return `${m.dashboard_ago_suffix()} ${diffDays}${m.dashboard_d_short()}`;
		} else {
			const dateLocale = getLocale() === 'es' ? 'es-MX' : 'en-US';
			return date.toLocaleDateString(dateLocale, { month: 'short', day: 'numeric' });
		}
	}
</script>

<Card.Root class={`overflow-hidden ${cls}`}>
	<Card.Header class="pb-3">
		<div class="flex items-center justify-between">
			<div>
				<Card.Title class="flex items-center gap-2">
					<Clock class="h-4 w-4 text-primary" />
					{m.dashboard_recent_activity()}
				</Card.Title>
				<Card.Description class="mt-0.5">{m.dashboard_latest_operations()}</Card.Description>
			</div>
			{#if activities.length > 0}
				<span class="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">{activities.length} {m.dashboard_records_suffix()}</span>
			{/if}
		</div>
	</Card.Header>
	<Card.Content>
		{#if activities.length === 0}
			<div class="flex flex-col items-center justify-center py-10 text-muted-foreground gap-3">
				<Clock class="h-8 w-8 opacity-30" />
				<p class="text-sm">{m.dashboard_no_recent_activity()}</p>
			</div>
		{:else}
			<div class="relative">
				<!-- Timeline connector line -->
				<div class="absolute left-[18px] top-2 bottom-2 w-px bg-border"></div>

				<div class="space-y-1">
					{#each activities as activity, idx}
						{@const Icon = getIcon(activity.type)}
						<div class="flex items-start gap-3 relative py-2 rounded-lg px-1 hover:bg-muted/40 transition-colors">
							<div class="mt-0.5 z-10">
								<div class="p-1.5 rounded-lg bg-background border border-border shadow-sm">
									<Icon class="h-3.5 w-3.5 text-primary" />
								</div>
							</div>
							<div class="flex-1 min-w-0 pt-0.5">
								<div class="flex items-start justify-between gap-2">
									<p class="text-sm font-medium leading-snug">{activity.title}</p>
									<span class="text-[11px] text-muted-foreground whitespace-nowrap shrink-0">
										{formatDate(activity.timestamp)}
									</span>
								</div>
								{#if activity.description}
									<p class="text-xs text-muted-foreground mt-0.5">{activity.description}</p>
								{/if}
							</div>
						</div>
					{/each}
				</div>
			</div>
		{/if}
	</Card.Content>
</Card.Root>
