<script lang="ts">
	import { ArrowLeft, Tags, Trash2 } from '@lucide/svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	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 Concept, type ConceptInput, type SatCatalogItem } from '$lib/api/fin';
	import { toast } from 'svelte-sonner';

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

	let concept = $state<Concept | null>(null);
	let form = $state<ConceptInput>({ code: '', description: '', product_service_id: 0 });
	let productService = $state<SatCatalogItem | null>(null);
	let productServiceError = $state('');
	let loading = $state(false);
	let saving = $state(false);

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

	function hydrate(c: Concept) {
		form = {
			code: c.code,
			description: c.description,
			product_service_id: c.product_service_id,
			unit_of_measure_id: c.unit_of_measure_id,
			tax_object_id: c.tax_object_id,
			unit_price: c.unit_price,
			currency: c.currency,
			is_active: c.is_active,
			notes: c.notes ?? ''
		};
		productService = c.product_service;
		productServiceError = '';
	}

	async function load(cid: number, id: number) {
		loading = true;
		try {
			concept = await conceptsAPI.get(id, cid);
			hydrate(concept);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cargar el concepto');
		} finally {
			loading = false;
		}
	}

	async function save(event: SubmitEvent) {
		event.preventDefault();
		const cid = companyId;
		if (!cid || !concept) 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 {
			concept = await conceptsAPI.update(
				concept.id,
				{
					...form,
					unit_price:
						form.unit_price === null || form.unit_price === undefined
							? null
							: Number(form.unit_price),
					notes: form.notes?.trim() ? form.notes : null
				},
				cid
			);
			hydrate(concept);
			toast.success('Cambios guardados');
		} catch (e) {
			const message = e instanceof Error ? e.message : 'No se pudieron guardar los cambios';
			// 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;
		}
	}

	async function remove() {
		const cid = companyId;
		if (!cid || !concept) 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 goto('/dashboard/fin/conceptos');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo dar de baja el concepto');
		}
	}
</script>

<svelte:head>
	<title>{concept ? `Concepto ${concept.code}` : '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>

	{#if loading && !concept}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if concept}
		<div class="flex flex-wrap items-start justify-between gap-3">
			<div>
				<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
					<Tags class="h-6 w-6" />
					{concept.code}
				</h1>
				<p class="mt-1 text-sm text-muted-foreground">
					{concept.description}
					{#if concept.product_service}
						· <span class="font-mono">{concept.product_service.code}</span>
					{/if}
					· {concept.is_active ? 'Activo' : 'Inactivo'}
				</p>
			</div>
			<Button variant="outline" onclick={remove}>
				<Trash2 class="mr-1 h-4 w-4 text-destructive" /> Dar de baja
			</Button>
		</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 border-t pt-4">
						<Button type="submit" disabled={saving}
							>{saving ? 'Guardando…' : 'Guardar cambios'}</Button
						>
					</div>
				</form>
			</Card.Content>
		</Card.Root>
	{/if}
</div>
