<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 { quotesAPI, accountsAPI, serviceRequestsAPI, type QuoteInput, type Account, type ServiceRequest } from '$lib/api/crm';
	import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
	import { toast } from 'svelte-sonner';

	let form = $state<QuoteInput>({ currency: 'USD', issue_date: new Date().toISOString().slice(0, 10) });
	let accounts = $state<Account[]>([]);
	let requests = $state<ServiceRequest[]>([]);
	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, requests] = await Promise.all([accountsAPI.list(cid), serviceRequestsAPI.list(cid)]);
		})();
	});

	async function save() {
		if (!companyId) return;
		saving = true;
		try {
			const created = await quotesAPI.create(form, companyId);
			toast.success('Cotización creada');
			await goto(`/dashboard/crm/cotizaciones/${created.id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo crear la cotización');
		} 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/crm/cotizaciones"><ArrowLeft class="mr-1 h-4 w-4" /> Cotizaciones</Button>
	<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Receipt class="h-6 w-6" /> Nueva cotización</h1>

	<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} bind:value={form.reference} placeholder="COT-0001" /></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">Solicitud (RFQ)</span><select class={inputCls} bind:value={form.service_request_id}><option value={undefined}>—</option>{#each requests as r (r.id)}<option value={r.id}>{r.reference ?? `#${r.id}`}</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">Fecha de la cotización</span><input type="date" class={inputCls} bind:value={form.issue_date} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Vigencia</span><input type="date" class={inputCls} bind:value={form.valid_until} /></label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Notas</span><textarea rows="2" class={inputCls} bind:value={form.notes}></textarea></label>
			</div>
			<div class="mt-6 flex justify-end gap-2 border-t pt-4">
				<Button variant="outline" href="/dashboard/crm/cotizaciones">Cancelar</Button>
				<Button onclick={save} disabled={saving || !companyId}>{saving ? 'Guardando…' : 'Crear y agregar conceptos'}</Button>
			</div>
		</Card.Content>
	</Card.Root>
</div>
