<script lang="ts">
	import { Tags, Plus, Trash2, 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 { conceptsAPI, type Concept } from '$lib/api/fin';
	import { toast } from 'svelte-sonner';

	let items = $state<Concept[]>([]);
	let loading = $state(false);
	let search = $state('');
	let activeFilter = $state<'todos' | 'activos' | 'inactivos'>('todos');

	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 {
			items = await conceptsAPI.list(cid, {
				search: search.trim() || undefined,
				active_only: activeFilter === 'todos' ? undefined : activeFilter === 'activos'
			});
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los conceptos');
		} finally {
			loading = false;
		}
	}

	async function remove(concept: Concept) {
		const cid = companyId;
		if (!cid) return;
		if (!confirm(`¿Dar de baja el concepto "${concept.code}"?`)) return;
		try {
			await conceptsAPI.remove(concept.id, cid);
			toast.success('Concepto dado de baja');
			await load(cid);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo dar de baja el concepto');
		}
	}

	function money(value: number | null): string {
		if (value === null || value === undefined) return '—';
		return new Intl.NumberFormat('es-MX', { minimumFractionDigits: 2 }).format(Number(value));
	}

	const inputCls =
		'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
</script>

<svelte:head>
	<title>Conceptos de facturación</title>
</svelte:head>

<div class="space-y-6">
	<div class="flex flex-wrap items-center justify-between gap-3">
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
				<Tags class="h-6 w-6" />
				Conceptos de facturación
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">
				Cada concepto se liga a una clave de producto/servicio del SAT, que no puede repetirse en la
				empresa.
			</p>
		</div>
		<Button href="/dashboard/fin/conceptos/nuevo" disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nuevo concepto
		</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="flex flex-wrap items-center gap-3">
				<div class="relative max-w-sm flex-1">
					<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
					<input
						class="w-full py-2 pr-3 pl-8 {inputCls}"
						placeholder="Buscar por clave o descripción…"
						bind:value={search}
						onchange={() => companyId && load(companyId)}
					/>
				</div>
				<select
					class="{inputCls} max-w-xs"
					bind:value={activeFilter}
					onchange={() => companyId && load(companyId)}
				>
					<option value="todos">Todos</option>
					<option value="activos">Solo activos</option>
					<option value="inactivos">Solo inactivos</option>
				</select>
			</div>
		</Card.Header>
		<Card.Content>
			{#if loading}
				<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
			{:else if items.length === 0}
				<p class="py-6 text-center text-sm text-muted-foreground">Sin conceptos registrados.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Clave</Table.Head>
								<Table.Head>Descripción</Table.Head>
								<Table.Head>Clave ProdServ</Table.Head>
								<Table.Head>Unidad</Table.Head>
								<Table.Head>Objeto de impuesto</Table.Head>
								<Table.Head class="text-right">Precio unitario</Table.Head>
								<Table.Head>Estado</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each items as concept (concept.id)}
								<Table.Row>
									<Table.Cell class="font-mono text-xs font-medium">
										<a class="hover:underline" href={`/dashboard/fin/conceptos/${concept.id}`}>
											{concept.code}
										</a>
									</Table.Cell>
									<Table.Cell>{concept.description}</Table.Cell>
									<Table.Cell class="text-xs">
										<span class="font-mono">{concept.product_service?.code ?? '—'}</span>
										{#if concept.product_service}
											<span class="block text-muted-foreground">
												{concept.product_service.description}
											</span>
										{/if}
									</Table.Cell>
									<Table.Cell class="text-xs">{concept.unit_of_measure?.name ?? '—'}</Table.Cell>
									<Table.Cell class="text-xs">{concept.tax_object?.code ?? '—'}</Table.Cell>
									<Table.Cell class="text-right">
										{money(concept.unit_price)}
										{concept.currency}
									</Table.Cell>
									<Table.Cell>
										<span
											class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {concept.is_active
												? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400'
												: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400'}"
										>
											{concept.is_active ? 'Activo' : 'Inactivo'}
										</span>
									</Table.Cell>
									<Table.Cell class="text-right">
										<Button
											variant="ghost"
											size="sm"
											href={`/dashboard/fin/conceptos/${concept.id}`}
											aria-label="Abrir"
										>
											<ChevronRight class="h-4 w-4" />
										</Button>
										<Button
											variant="ghost"
											size="sm"
											onclick={() => remove(concept)}
											aria-label="Dar de baja"
										>
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						</Table.Body>
					</Table.Root>
				</div>
			{/if}
		</Card.Content>
	</Card.Root>
</div>
