<script lang="ts">
	import { ArrowLeft, FolderKanban, Target, FileText, Receipt, Ship, DollarSign } from '@lucide/svelte';
	import { page } from '$app/state';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { casesAPI, type CaseWithTimeline } from '$lib/api/crm';
	import { formatDate } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	const caseId = $derived(Number(page.params.id));
	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	let data = $state<CaseWithTimeline | null>(null);
	let loading = $state(false);

	const STAGE_LABEL: Record<string, string> = {
		oportunidad: 'Oportunidad', solicitud: 'Solicitud', cotizacion: 'Cotización',
		operacion: 'Operación', facturacion: 'Facturación', cerrado: 'Cerrado'
	};
	const KIND: Record<string, { label: string; icon: any }> = {
		oportunidad: { label: 'Oportunidad', icon: Target },
		solicitud: { label: 'Solicitud', icon: FileText },
		cotizacion: { label: 'Cotización', icon: Receipt },
		operacion: { label: 'Operación / Embarque', icon: Ship },
		factura: { label: 'Factura', icon: DollarSign }
	};

	$effect(() => {
		const cid = companyId;
		const id = caseId;
		if (!cid || !id) return;
		void (async () => {
			loading = true;
			try { data = await casesAPI.get(id, cid); }
			catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo cargar el expediente'); }
			finally { loading = false; }
		})();
	});
</script>

<div class="space-y-6">
	<Button variant="ghost" size="sm" href="/dashboard/crm/expedientes"><ArrowLeft class="mr-1 h-4 w-4" /> Expedientes</Button>

	{#if loading && !data}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if data}
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FolderKanban class="h-6 w-6" /> <span class="font-mono">{data.reference ?? `Expediente #${data.id}`}</span></h1>
			<p class="mt-1 text-sm text-muted-foreground">Etapa: <b>{STAGE_LABEL[data.stage] ?? data.stage}</b> · {data.status}{#if data.title} · {data.title}{/if}</p>
		</div>

		<Card.Root>
			<Card.Header><Card.Title class="text-base">Historia del trámite</Card.Title>
				<Card.Description>Todos los documentos ligados a este expediente, en orden cronológico.</Card.Description>
			</Card.Header>
			<Card.Content>
				{#if data.timeline.length === 0}
					<p class="text-sm text-muted-foreground">Sin movimientos aún.</p>
				{:else}
					<ol class="relative ml-3 border-l pl-6">
						{#each data.timeline as ev (ev.kind + '-' + ev.id)}
							{@const K = KIND[ev.kind] ?? { label: ev.kind, icon: FileText }}
							<li class="mb-5">
								<span class="absolute -left-3 flex h-6 w-6 items-center justify-center rounded-full border bg-background">
									<K.icon class="h-3.5 w-3.5" />
								</span>
								<div class="flex flex-wrap items-center gap-2">
									<span class="text-xs uppercase text-muted-foreground">{K.label}</span>
									<a class="font-mono text-sm font-medium hover:underline" href={ev.url}>{ev.reference ?? `#${ev.id}`}</a>
									{#if ev.status}<span class="rounded-full bg-muted px-2 py-0.5 text-[10px]">{ev.status}</span>{/if}
									<span class="text-xs text-muted-foreground">{formatDate(ev.created_at)}</span>
								</div>
							</li>
						{/each}
					</ol>
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
