<script lang="ts">
	import * as Card from '$lib/components/ui/card';
	import KpiCard from '$lib/components/dashboard/kpi-card.svelte';
	import ChartCard from '$lib/components/dashboard/chart-card.svelte';
	import ActivityFeed from '$lib/components/dashboard/activity-feed.svelte';
	import TrendChart from '$lib/components/dashboard/trend-chart.svelte';
	import DonutChart from '$lib/components/dashboard/donut-chart.svelte';
	import { getDashboardStats } from '$lib/api/dashboard';
	import { companyStore } from '$lib/stores/company.svelte';
	import { onMount } from 'svelte';
	import {
		FileText,
		Users,
		Package,
		Clock,
		BarChart3,
		Calendar,
		CircleAlert,
		RefreshCw
	} from 'lucide-svelte';
	import type { DashboardStats } from '$lib/api/dashboard/types';
	import { Button } from '$lib/components/ui/button';
	import * as Alert from '$lib/components/ui/alert';
	import { m } from '$lib/i18n/messages';
	import { getLocale } from '$lib/paraglide/runtime';

	let stats = $state<DashboardStats | null>(null);
	let loading = $state(true);
	let error = $state<string | null>(null);

	let greeting = $derived(() => {
		const hour = new Date().getHours();
		if (hour < 12) return m.dashboard_greeting_morning();
		if (hour < 18) return m.dashboard_greeting_afternoon();
		return m.dashboard_greeting_evening();
	});

	async function loadDashboardData() {
		if (!companyStore.activeCompany) {
			error = m.dashboard_no_active_company();
			loading = false;
			return;
		}

		try {
			loading = true;
			error = null;
			stats = await getDashboardStats(companyStore.activeCompany.id);
		} catch (err) {
			console.error('Error loading dashboard:', err);
			error = err instanceof Error ? err.message : m.dashboard_load_error();
		} finally {
			loading = false;
		}
	}

	const dateLocale = $derived(getLocale() === 'es' ? 'es-MX' : 'en-US');

	// Reaccionar cuando cambie la compañía activa
	$effect(() => {
		if (companyStore.activeCompany) {
			loadDashboardData();
		}
	});
</script>

<div class="space-y-6">
	{#snippet headerSection()}
		<div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
			<div>
				<div class="flex items-center gap-2 text-xs text-muted-foreground mb-1">
					<span>{m.sidebar_dashboard()}</span>
					{#if stats?.company_name}
						<span>/</span>
						<span class="text-primary font-medium">{stats.company_name}</span>
					{/if}
				</div>
				<h1 class="text-2xl font-bold tracking-tight text-foreground">
					{greeting()}{m.dashboard_team_suffix()}
				</h1>
				<p class="text-muted-foreground text-sm mt-0.5">
					{#if stats?.company_name}
						<span class="inline-flex items-center gap-1.5">
							<span class="inline-block w-2 h-2 rounded-full bg-emerald-500"></span>
							{m.dashboard_operational_summary()}
						</span>
					{:else}
						{m.dashboard_management_system()}
					{/if}
				</p>
			</div>
			<div class="flex items-center gap-2">
				<Button variant="ghost" size="sm" class="hidden sm:flex text-muted-foreground">
					<Calendar class="mr-1.5 h-3.5 w-3.5" />
					{new Date().toLocaleDateString(dateLocale, { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })}
				</Button>
				<Button onclick={loadDashboardData} variant="outline" size="sm" disabled={loading}>
					<RefreshCw class={`h-3.5 w-3.5 mr-1.5 ${loading ? 'animate-spin' : ''}`} />
					{loading ? m.dashboard_loading() : m.dashboard_update()}
				</Button>
			</div>
		</div>
	{/snippet}

	{@render headerSection()}

	{#if error}
		<Alert.Root variant="destructive">
			<CircleAlert class="h-4 w-4" />
			<Alert.Title>{m.exchange_rate_error_title()}</Alert.Title>
			<Alert.Description>{error}</Alert.Description>
		</Alert.Root>
	{/if}

	{#if loading}
		<!-- KPI skeleton -->
		<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
			{#each Array(6) as _}
				<div class="flex items-center gap-4 rounded-xl border bg-card px-4 py-3.5 animate-pulse">
					<div class="h-9 w-9 rounded-lg bg-muted shrink-0"></div>
					<div class="flex-1 space-y-2">
						<div class="h-3 w-24 bg-muted rounded-full"></div>
						<div class="h-5 w-16 bg-muted rounded-md"></div>
					</div>
				</div>
			{/each}
		</div>
		<!-- Chart skeleton -->
		<div class="grid gap-4 lg:grid-cols-2">
			{#each Array(2) as _}
				<Card.Root class="animate-pulse">
					<Card.Header>
						<div class="h-4 w-40 bg-muted rounded-full"></div>
						<div class="h-3 w-56 bg-muted rounded-full mt-2"></div>
					</Card.Header>
					<Card.Content>
						<div class="h-56 bg-muted rounded-lg"></div>
					</Card.Content>
				</Card.Root>
			{/each}
		</div>
	{:else if stats}
		<!--
			Bento grid:
			┌──────┬──────┬──────┬──────┬──────┬──────┐  row 1 — KPIs
			├────────────────────────┬─────────────────┤  row 2
			│  TrendChart  (8)       │  Donut    (4)   │
			├───────────────┬────────┴─┬───────────────┤  row 3
			│ Clientes (4)  │Proveed(4) │ Accesos  (4)  │
			├────────────────────────┬─────────────────┤  row 4
			│  ActivityFeed  (8, x3) │  Documentos (4) │
			│                        ├─────────────────┤  row 5
			│                        │  Contactos  (4) │
			│                        ├─────────────────┤  row 6
			│                        │  Items      (4) │
			└────────────────────────┴─────────────────┘
		-->
		<div class="grid grid-cols-2 md:grid-cols-6 lg:grid-cols-12 gap-3">

			<!-- ── Row 1: KPI tiles ── -->
			<div class="col-span-1 md:col-span-2 lg:col-span-2">
				<KpiCard metric={{...stats.total_invoices, label: m.dashboard_invoices()}} icon={FileText} iconColor="text-blue-600" />
			</div>
			<div class="col-span-1 md:col-span-2 lg:col-span-2">
				<KpiCard metric={{...stats.total_pedimentos, label: m.dashboard_pedimentos()}} icon={FileText} iconColor="text-green-600" />
			</div>
			<div class="col-span-1 md:col-span-2 lg:col-span-2">
				<KpiCard metric={{...stats.total_clients, label: m.dashboard_clients()}} icon={Users} iconColor="text-purple-600" />
			</div>
			<div class="col-span-1 md:col-span-2 lg:col-span-2">
				<KpiCard metric={{...stats.total_providers, label: m.dashboard_providers()}} icon={Users} iconColor="text-orange-600" />
			</div>
			<div class="col-span-1 md:col-span-3 lg:col-span-2">
				<KpiCard metric={{...stats.active_items, label: m.dashboard_active_items_stat()}} icon={Package} iconColor="text-cyan-600" />
			</div>
			<div class="col-span-1 md:col-span-3 lg:col-span-2">
				<KpiCard metric={{...stats.pending_approvals, label: m.dashboard_pending_approvals()}} icon={Clock} iconColor="text-yellow-600" />
			</div>

			<!-- ── Row 2: TrendChart (8) | Donut (4) — altura natural, sin row-span ── -->
			<div class="col-span-2 md:col-span-4 lg:col-span-8">
				<TrendChart monthlyData={stats.invoices_by_month} class="h-full" />
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4">
				<DonutChart title={m.dashboard_operations_distribution()} data={stats.operations_by_type} class="h-full" />
			</div>

			<!-- ── Row 3: Clientes (4) | Proveedores (4) | Accesos Rápidos (4) ── -->
			<div class="col-span-2 md:col-span-2 lg:col-span-4">
				<ChartCard
					title={m.dashboard_top_clients()}
					description={m.dashboard_by_invoice_number()}
					data={stats.top_clients}
					type="bar"
					class="h-full"
				/>
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4">
				<ChartCard
					title={m.dashboard_top_providers()}
					description={m.dashboard_by_invoice_number()}
					data={stats.top_providers}
					type="bar"
					class="h-full"
				/>
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4">
				<Card.Root class="h-full overflow-hidden">
					<Card.Header class="pb-3">
						<Card.Title class="text-base">{m.dashboard_quick_access()}</Card.Title>
						<Card.Description>{m.dashboard_most_used_modules()}</Card.Description>
					</Card.Header>
					<Card.Content class="space-y-1.5">
						<a href="/dashboard/invoices" class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent hover:border-primary/30 transition-all group">
							<div class="p-1.5 rounded-md bg-blue-50 dark:bg-blue-950/40 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/40 transition-colors">
								<FileText class="h-4 w-4 text-blue-600" />
							</div>
							<div class="flex-1 min-w-0">
								<div class="text-sm font-medium">{m.dashboard_invoices()}</div>
								<div class="text-xs text-muted-foreground">{m.dashboard_manage_invoices()}</div>
							</div>
							<span class="text-muted-foreground/40 group-hover:text-primary transition-colors text-lg leading-none">&rsaquo;</span>
						</a>
						<a href="/dashboard/clients_and_providers" class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent hover:border-primary/30 transition-all group">
							<div class="p-1.5 rounded-md bg-purple-50 dark:bg-purple-950/40 group-hover:bg-purple-100 dark:group-hover:bg-purple-900/40 transition-colors">
								<Users class="h-4 w-4 text-purple-600" />
							</div>
							<div class="flex-1 min-w-0">
								<div class="text-sm font-medium">{m.dashboard_clients_and_providers()}</div>
								<div class="text-xs text-muted-foreground">{m.dashboard_manage_contacts()}</div>
							</div>
							<span class="text-muted-foreground/40 group-hover:text-primary transition-colors text-lg leading-none">&rsaquo;</span>
						</a>
						<a href="/dashboard/goods" class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent hover:border-primary/30 transition-all group">
							<div class="p-1.5 rounded-md bg-cyan-50 dark:bg-cyan-950/40 group-hover:bg-cyan-100 dark:group-hover:bg-cyan-900/40 transition-colors">
								<Package class="h-4 w-4 text-cyan-600" />
							</div>
							<div class="flex-1 min-w-0">
								<div class="text-sm font-medium">{m.dashboard_goods()}</div>
								<div class="text-xs text-muted-foreground">{m.dashboard_product_catalog()}</div>
							</div>
							<span class="text-muted-foreground/40 group-hover:text-primary transition-colors text-lg leading-none">&rsaquo;</span>
						</a>
						<a href="/dashboard/reference_data/code_pedimento_regimens" class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent hover:border-primary/30 transition-all group">
							<div class="p-1.5 rounded-md bg-orange-50 dark:bg-orange-950/40 group-hover:bg-orange-100 dark:group-hover:bg-orange-900/40 transition-colors">
								<BarChart3 class="h-4 w-4 text-orange-600" />
							</div>
							<div class="flex-1 min-w-0">
								<div class="text-sm font-medium">{m.dashboard_reference_data()}</div>
								<div class="text-xs text-muted-foreground">{m.dashboard_sat_catalogs()}</div>
							</div>
							<span class="text-muted-foreground/40 group-hover:text-primary transition-colors text-lg leading-none">&rsaquo;</span>
						</a>
					</Card.Content>
				</Card.Root>
			</div>

			<!-- ── Rows 4-6: ActivityFeed (8, row-span-3) | 3 stat tiles ── -->
			<div class="col-span-2 md:col-span-4 lg:col-span-8 lg:row-span-3">
				<ActivityFeed activities={stats.recent_activity} class="h-full" />
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4 rounded-xl border bg-card p-5 flex flex-col items-center justify-center text-center">
				<div class="text-3xl font-bold text-foreground tabular-nums">
					{(stats.total_invoices.value + stats.total_pedimentos.value).toLocaleString()}
				</div>
				<div class="text-xs text-muted-foreground mt-1.5 font-medium uppercase tracking-wide">{m.dashboard_total_documents()}</div>
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4 rounded-xl border bg-card p-5 flex flex-col items-center justify-center text-center">
				<div class="text-3xl font-bold text-foreground tabular-nums">
					{(stats.total_clients.value + stats.total_providers.value).toLocaleString()}
				</div>
				<div class="text-xs text-muted-foreground mt-1.5 font-medium uppercase tracking-wide">{m.dashboard_total_contacts()}</div>
			</div>
			<div class="col-span-2 md:col-span-2 lg:col-span-4 rounded-xl border bg-card p-5 flex flex-col items-center justify-center text-center">
				<div class="text-3xl font-bold text-foreground tabular-nums">
					{stats.active_items.value.toLocaleString()}
				</div>
				<div class="text-xs text-muted-foreground mt-1.5 font-medium uppercase tracking-wide">{m.dashboard_active_items_stat()}</div>
			</div>

		</div>
	{/if}
</div>
