<script lang="ts">
	import { ArrowLeft, Tags } from '@lucide/svelte';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import ConceptFields from '$lib/components/fin/ConceptFields.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { conceptsAPI, type ConceptInput, type SatCatalogItem } from '$lib/api/fin';
	import { toast } from 'svelte-sonner';

	let form = $state<ConceptInput>({
		code: '',
		description: '',
		product_service_id: 0,
		unit_of_measure_id: null,
		tax_object_id: null,
		unit_price: null,
		currency: 'MXN',
		is_active: true,
		notes: ''
	});
	let productService = $state<SatCatalogItem | null>(null);
	let productServiceError = $state('');
	let saving = $state(false);

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

	async function save(event: SubmitEvent) {
		event.preventDefault();
		const cid = companyId;
		if (!cid) return;
		if (!form.code.trim() || !form.description.trim()) {
			toast.error('La clave y la descripción son obligatorias');
			return;
		}
		if (!form.product_service_id) {
			productServiceError = 'Selecciona la clave de producto/servicio del SAT';
			return;
		}
		saving = true;
		productServiceError = '';
		try {
			const created = await conceptsAPI.create(
				{
					...form,
					unit_price:
						form.unit_price === null || form.unit_price === undefined
							? null
							: Number(form.unit_price),
					notes: form.notes?.trim() ? form.notes : null
				},
				cid
			);
			toast.success('Concepto creado');
			await goto(`/dashboard/fin/conceptos/${created.id}`);
		} catch (e) {
			const message = e instanceof Error ? e.message : 'No se pudo crear el concepto';
			// El 409 del backend por clave ProdServ ya asignada se muestra junto al campo.
			if (message.toLowerCase().includes('producto/servicio')) productServiceError = message;
			else toast.error(message);
		} finally {
			saving = false;
		}
	}
</script>

<svelte:head>
	<title>Nuevo concepto de facturación</title>
</svelte:head>

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

	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<Tags class="h-6 w-6" /> Nuevo concepto
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">
			Cada concepto se liga a una clave de producto/servicio del SAT.
		</p>
	</div>

	<Card.Root>
		<Card.Content class="pt-6">
			<form onsubmit={save}>
				<ConceptFields bind:form bind:productService bind:productServiceError {companyId} />

				<div class="mt-6 flex justify-end gap-2 border-t pt-4">
					<Button type="button" variant="outline" href="/dashboard/fin/conceptos">Cancelar</Button>
					<Button type="submit" disabled={saving || !companyId}
						>{saving ? 'Guardando…' : 'Crear'}</Button
					>
				</div>
			</form>
		</Card.Content>
	</Card.Root>
</div>
