<script lang="ts">
	import { Briefcase, Building2, Users, UserPlus, Target, CalendarClock } from '@lucide/svelte';
	import * as Card from '$lib/components/ui/card';
	import KpiCard from '$lib/components/dashboard/kpi-card.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { metricsAPI, type CrmMetrics } from '$lib/api/crm';
	import { formatMoney } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	let metrics = $state<CrmMetrics | null>(null);
	let loading = $state(false);

	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	$effect(() => {
		const cid = companyId;
		if (!cid) return;
		void load(cid);
	});

	async function load(cid: number) {
		loading = true;
		try {
			metrics = await metricsAPI.get(cid);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar las métricas');
		} finally {
			loading = false;
		}
	}

	const maxStageValue = $derived(
		metrics && metrics.by_stage.length
			? Math.max(1, ...metrics.by_stage.map((s) => Number(s.value)))
			: 1
	);
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<Briefcase class="h-6 w-6" />
			CRM
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">Panel comercial: cuentas, prospectos y pipeline de ventas.</p>
	</div>

	{#if !companyId}
		<Card.Root>
			<Card.Content class="py-8 text-center text-sm text-muted-foreground">
				Selecciona una compañía para ver las métricas del CRM.
			</Card.Content>
		</Card.Root>
	{:else if metrics}
		<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
			<KpiCard metric={{ label: 'Cuentas', value: metrics.total_accounts }} icon={Building2} iconColor="text-blue-600" />
			<KpiCard metric={{ label: 'Contactos', value: metrics.total_contacts }} icon={Users} iconColor="text-cyan-600" />
			<KpiCard metric={{ label: 'Prospectos abiertos', value: metrics.open_leads }} icon={UserPlus} iconColor="text-purple-600" />
			<KpiCard metric={{ label: 'Oportunidades abiertas', value: metrics.open_opportunities }} icon={Target} iconColor="text-orange-600" />
			<KpiCard metric={{ label: 'Actividades pendientes', value: metrics.pending_activities }} icon={CalendarClock} iconColor="text-yellow-600" />
		</div>

		<div class="grid gap-4 md:grid-cols-2">
			<Card.Root>
				<Card.Header>
					<Card.Description>Valor del pipeline abierto</Card.Description>
					<Card.Title class="text-2xl">{formatMoney(metrics.open_pipeline_value)}</Card.Title>
				</Card.Header>
			</Card.Root>
			<Card.Root>
				<Card.Header>
					<Card.Description>Ganado ({metrics.won_opportunities} oportunidades)</Card.Description>
					<Card.Title class="text-2xl text-emerald-600">{formatMoney(metrics.won_value)}</Card.Title>
				</Card.Header>
			</Card.Root>
		</div>

		<Card.Root>
			<Card.Header>
				<Card.Title>Embudo de ventas</Card.Title>
				<Card.Description>Oportunidades abiertas por etapa</Card.Description>
			</Card.Header>
			<Card.Content>
				{#if metrics.by_stage.length === 0}
					<p class="text-sm text-muted-foreground">
						Aún no hay etapas configuradas. Crea un embudo desde Oportunidades.
					</p>
				{:else}
					<div class="space-y-3">
						{#each metrics.by_stage as stage (stage.stage_id)}
							<div>
								<div class="mb-1 flex items-center justify-between text-sm">
									<span class="font-medium">{stage.stage_name}</span>
									<span class="text-muted-foreground">
										{stage.count} · {formatMoney(stage.value)}
									</span>
								</div>
								<div class="h-2.5 w-full overflow-hidden rounded-full bg-muted">
									<div
										class="h-full rounded-full bg-primary transition-all"
										style="width: {Math.round((Number(stage.value) / maxStageValue) * 100)}%"
									></div>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</Card.Content>
		</Card.Root>
	{:else if loading}
		<p class="text-sm text-muted-foreground">Cargando métricas…</p>
	{/if}
</div>
