<script lang="ts">
	import { FolderKanban, Search, ChevronRight } from '@lucide/svelte';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { casesAPI, accountsAPI, type Case, type Account } from '$lib/api/crm';
	import { formatDate } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	const STAGE_LABEL: Record<string, string> = {
		oportunidad: 'Oportunidad', solicitud: 'Solicitud', cotizacion: 'Cotización',
		operacion: 'Operación', facturacion: 'Facturación', cerrado: 'Cerrado'
	};

	let items = $state<Case[]>([]);
	let accounts = $state<Account[]>([]);
	let loading = $state(false);
	let search = $state('');

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	function accountName(id: number | null): string {
		return accounts.find((a) => a.id === id)?.name ?? '—';
	}
	const filtered = $derived(
		search.trim()
			? items.filter((c) => `${c.reference ?? ''} ${c.title ?? ''} ${accountName(c.account_id)}`.toLowerCase().includes(search.trim().toLowerCase()))
			: items
	);

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

	async function load(cid: number) {
		loading = true;
		try {
			[items, accounts] = await Promise.all([casesAPI.list(cid), accountsAPI.list(cid)]);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los expedientes');
		} finally {
			loading = false;
		}
	}
	const inputCls = 'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FolderKanban class="h-6 w-6" /> Expedientes</h1>
		<p class="mt-1 text-sm text-muted-foreground">Referencia única que hila todo el trámite (oportunidad → solicitud → cotización → operación → factura).</p>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="relative max-w-sm">
				<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
				<input class="w-full py-2 pl-8 pr-3 {inputCls}" placeholder="Buscar por folio o cliente…" bind:value={search} />
			</div>
		</Card.Header>
		<Card.Content>
			{#if loading}
				<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
			{:else if filtered.length === 0}
				<p class="py-6 text-center text-sm text-muted-foreground">Sin expedientes. Se crean automáticamente al generar una oportunidad.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Expediente</Table.Head>
								<Table.Head>Cliente</Table.Head>
								<Table.Head>Etapa</Table.Head>
								<Table.Head>Estatus</Table.Head>
								<Table.Head>Creado</Table.Head>
								<Table.Head></Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as c (c.id)}
								<Table.Row>
									<Table.Cell class="font-mono font-medium"><a class="hover:underline" href={`/dashboard/crm/expedientes/${c.id}`}>{c.reference ?? `#${c.id}`}</a></Table.Cell>
									<Table.Cell>{accountName(c.account_id)}</Table.Cell>
									<Table.Cell>{STAGE_LABEL[c.stage] ?? c.stage}</Table.Cell>
									<Table.Cell>{c.status}</Table.Cell>
									<Table.Cell>{formatDate(c.created_at)}</Table.Cell>
									<Table.Cell class="text-right"><Button variant="ghost" size="sm" href={`/dashboard/crm/expedientes/${c.id}`} aria-label="Abrir"><ChevronRight class="h-4 w-4" /></Button></Table.Cell>
								</Table.Row>
							{/each}
						</Table.Body>
					</Table.Root>
				</div>
			{/if}
		</Card.Content>
	</Card.Root>
</div>
