<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';

	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 'Buenos días';
		if (hour < 18) return 'Buenas tardes';
		return 'Buenas noches';
	});

	async function loadDashboardData() {
		if (!companyStore.activeCompany) {
			error = 'No hay compañía activa seleccionada';
			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 : 'Error al cargar el dashboard';
		} finally {
			loading = false;
		}
	}

	// 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>				
				<h1 class="text-3xl font-bold tracking-tight text-foreground">
					{greeting()}, equipo.
				</h1>
				<p class="text-muted-foreground mt-1 flex items-center gap-2">
					{#if stats?.company_name}
						<span class="font-semibold text-primary">{stats.company_name}</span> 
						<span class="text-xs bg-muted px-2 py-0.5 rounded-full">Anexos 22/24/30</span>
					{:else}
						Sistema de gestión de comercio exterior
					{/if}
				</p>
			</div>
			<div class="flex items-center gap-2">
				<Button variant="outline" size="sm" class="hidden sm:flex">
					<Calendar class="mr-2 h-4 w-4" />
					Hoy: {new Date().toLocaleDateString()}
				</Button>
				<Button onclick={loadDashboardData} variant="outline" disabled={loading}>
					<RefreshCw class={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
					{loading ? 'Cargando...' : 'Actualizar'}
				</Button>
			</div>
		</div>
	{/snippet}

	{@render headerSection()}

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

	{#if loading}
		<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
			{#each Array(6) as _}
				<Card.Root class="animate-pulse">
					<Card.Header class="space-y-2">
						<div class="h-4 w-24 bg-muted rounded"></div>
					</Card.Header>
					<Card.Content>
						<div class="h-8 w-16 bg-muted rounded"></div>
					</Card.Content>
				</Card.Root>
			{/each}
		</div>
	{:else if stats}
		<!-- KPIs Grid -->
		<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
			<KpiCard metric={stats.total_invoices} icon={FileText} iconColor="text-blue-600" />
			<KpiCard metric={stats.total_pedimentos} icon={FileText} iconColor="text-green-600" />
			<KpiCard metric={stats.total_clients} icon={Users} iconColor="text-purple-600" />
			<KpiCard metric={stats.total_providers} icon={Users} iconColor="text-orange-600" />
			<KpiCard metric={stats.active_items} icon={Package} iconColor="text-cyan-600" />
			<KpiCard metric={stats.pending_approvals} icon={Clock} iconColor="text-yellow-600" />
		</div>

		<!-- Main Charts -->
		<div class="grid gap-4 lg:grid-cols-2">
			<TrendChart monthlyData={stats.invoices_by_month} />
			<DonutChart title="Distribución de Operaciones" data={stats.operations_by_type} />
		</div>

		<!-- Analytics Row -->
		<div class="grid gap-4 md:grid-cols-2">
			<ChartCard
				title="Top 5 Clientes"
				description="Por número de facturas"
				data={stats.top_clients}
				type="bar"
			/>
			<ChartCard
				title="Top 5 Proveedores"
				description="Por número de facturas"
				data={stats.top_providers}
				type="bar"
			/>
		</div>

		<!-- Activity Feed & Quick Actions -->
		<div class="grid gap-4 lg:grid-cols-3">
			<div class="lg:col-span-2">
				<ActivityFeed activities={stats.recent_activity} />
			</div>

			<!-- Quick Actions -->
			<Card.Root>
				<Card.Header>
					<Card.Title>Accesos Rápidos</Card.Title>
					<Card.Description>Funciones más utilizadas</Card.Description>
				</Card.Header>
				<Card.Content class="space-y-2">
					<a
						href="/dashboard/invoices"
						class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent transition-colors"
					>
						<FileText class="h-5 w-5 text-primary" />
						<div class="flex-1 min-w-0">
							<div class="text-sm font-medium">Facturas</div>
							<div class="text-xs text-muted-foreground">Gestionar facturas</div>
						</div>
					</a>

					<a
						href="/dashboard/clients_and_providers"
						class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent transition-colors"
					>
						<Users class="h-5 w-5 text-primary" />
						<div class="flex-1 min-w-0">
							<div class="text-sm font-medium">Clientes y Proveedores</div>
							<div class="text-xs text-muted-foreground">Administrar contactos</div>
						</div>
					</a>

					<a
						href="/dashboard/goods"
						class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent transition-colors"
					>
						<Package class="h-5 w-5 text-primary" />
						<div class="flex-1 min-w-0">
							<div class="text-sm font-medium">Mercancías</div>
							<div class="text-xs text-muted-foreground">Catálogo de productos</div>
						</div>
					</a>

					<a
						href="/dashboard/reference_data/code_pedimento_regimens"
						class="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent transition-colors"
					>
						<BarChart3 class="h-5 w-5 text-primary" />
						<div class="flex-1 min-w-0">
							<div class="text-sm font-medium">Datos de Referencia</div>
							<div class="text-xs text-muted-foreground">Catálogos del SAT</div>
						</div>
					</a>
				</Card.Content>
			</Card.Root>
		</div>

		<!-- Footer Info -->
		<Card.Root class="bg-muted/50">
			<Card.Content class="pt-6">
				<div class="grid gap-4 md:grid-cols-3 text-center">
					<div>
						<div class="text-2xl font-bold text-primary">
							{stats.total_invoices.value + stats.total_pedimentos.value}
						</div>
						<div class="text-xs text-muted-foreground mt-1">Total de Documentos</div>
					</div>
					<div>
						<div class="text-2xl font-bold text-primary">
							{stats.total_clients.value + stats.total_providers.value}
						</div>
						<div class="text-xs text-muted-foreground mt-1">Total de Contactos</div>
					</div>
					<div>
						<div class="text-2xl font-bold text-primary">{stats.active_items.value}</div>
						<div class="text-xs text-muted-foreground mt-1">Items Activos</div>
					</div>
				</div>
			</Card.Content>
		</Card.Root>
	{/if}
</div>
