<script lang="ts">
	import { ArrowLeft, Receipt } from '@lucide/svelte';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { invoicesAPI, type InvoiceInput } from '$lib/api/fin';
	import { accountsAPI, type Account } from '$lib/api/crm';
	import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
	import { toast } from 'svelte-sonner';

	let form = $state<InvoiceInput>({ currency: 'MXN', tax_rate: 16 });
	let accounts = $state<Account[]>([]);
	let saving = $state(false);
	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	$effect(() => {
		const cid = companyId;
		if (!cid) return;
		void crmCatalogs.preload(['moneda']);
		void (async () => { accounts = await accountsAPI.list(cid); })();
	});

	async function save() {
		if (!companyId) return;
		saving = true;
		try {
			const created = await invoicesAPI.create(form, companyId);
			toast.success('Factura creada');
			await goto(`/dashboard/fin/facturas/${created.id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo crear la factura');
		} finally {
			saving = 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">
	<Button variant="ghost" size="sm" href="/dashboard/fin/facturas"><ArrowLeft class="mr-1 h-4 w-4" /> Facturas</Button>
	<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Receipt class="h-6 w-6" /> Nueva factura</h1>
	<p class="text-sm text-muted-foreground">Tip: también puedes generar la factura automáticamente desde un embarque (botón en el embarque).</p>

	<Card.Root>
		<Card.Content class="pt-6">
			<div class="grid gap-4 sm:grid-cols-2">
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Folio</span><input class="{inputCls} bg-muted/40" bind:value={form.reference} readonly placeholder="Se genera automáticamente (F2026-08-001)" /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cliente</span><select class={inputCls} bind:value={form.account_id}><option value={undefined}>—</option>{#each accounts as a (a.id)}<option value={a.id}>{a.name}</option>{/each}</select></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda</span><select class={inputCls} bind:value={form.currency}>{#each crmCatalogs.options('moneda') as m (m.value)}<option value={m.value}>{m.value} — {m.label}</option>{/each}</select></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">% Impuesto (IVA)</span><input type="number" min="0" max="100" step="0.01" class={inputCls} bind:value={form.tax_rate} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Vencimiento</span><input type="date" class={inputCls} bind:value={form.due_date} /></label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Datos bancarios</span><textarea rows="2" class={inputCls} bind:value={form.bank_info}></textarea></label>
			</div>
			<div class="mt-6 flex justify-end gap-2 border-t pt-4">
				<Button variant="outline" href="/dashboard/fin/facturas">Cancelar</Button>
				<Button onclick={save} disabled={saving || !companyId}>{saving ? 'Guardando…' : 'Crear y agregar conceptos'}</Button>
			</div>
		</Card.Content>
	</Card.Root>
</div>
