<script lang="ts">
	import { onMount } from 'svelte';
	import { Calculator } 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 { rateSheetsAPI, type CostOption, type RateMode } from '$lib/api/crm/rates';
	import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
	import { formatMoney } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	const inputCls = 'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';

	let f = $state({
		mode: 'aereo' as RateMode, origin: '', destination: '', on_date: '',
		gross_weight_kg: null as number | null, volume_m3: null as number | null,
		equipment_type: '', quantity: 1, dangerous: false
	});
	let options = $state<CostOption[]>([]);
	let calculated = $state(false);
	let working = $state(false);

	const isFcl = $derived(f.mode === 'maritimo_fcl' || f.mode === 'terrestre');

	onMount(() => void crmCatalogs.preload(['modo_tarifario', 'tipo_equipo']));

	async function calc() {
		if (!companyId) return;
		if (!f.destination.trim()) { toast.error('Indica el destino'); return; }
		working = true; calculated = false;
		try {
			const res = await rateSheetsAPI.quote({
				mode: f.mode, origin: f.origin || null, destination: f.destination || null,
				on_date: f.on_date || null, gross_weight_kg: f.gross_weight_kg, volume_m3: f.volume_m3,
				equipment_type: f.equipment_type || null, quantity: f.quantity || 1, dangerous: f.dangerous
			}, companyId);
			options = res.options; calculated = true;
		} catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo calcular'); }
		finally { working = false; }
	}
	const money = (v: number, c: string | null) => formatMoney(v, c ?? 'USD');
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Calculator class="h-6 w-6" /> Cotizador</h1>
		<p class="mt-1 text-sm text-muted-foreground">Calcula el costo por proveedor a partir de los tarifarios vigentes.</p>
	</div>

	{#if !companyId}
		<Card.Root><Card.Content class="pt-6 text-sm text-muted-foreground">Selecciona una compañía activa.</Card.Content></Card.Root>
	{:else}
		<Card.Root>
			<Card.Header><Card.Title class="text-base">Datos de la carga</Card.Title></Card.Header>
			<Card.Content>
				<div class="grid gap-4 sm:grid-cols-3">
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Modo *</span>
						<select class={inputCls} bind:value={f.mode}>{#each crmCatalogs.options('modo_tarifario') as m (m.value)}<option value={m.value}>{m.label}</option>{/each}</select>
					</label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Origen</span><input class={inputCls} bind:value={f.origin} placeholder="NLU / MXZLO" /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Destino *</span><input class={inputCls} bind:value={f.destination} placeholder="FRA / CNSHA" /></label>

					{#if isFcl}
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de equipo</span>
							<select class={inputCls} bind:value={f.equipment_type}><option value="">—</option>{#each crmCatalogs.options('tipo_equipo') as t (t.value)}<option value={t.value}>{t.label}</option>{/each}</select>
						</label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cantidad</span><input type="number" min="1" class={inputCls} bind:value={f.quantity} /></label>
					{:else}
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Peso bruto (kg)</span><input type="number" min="0" step="0.01" class={inputCls} bind:value={f.gross_weight_kg} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Volumen (m³)</span><input type="number" min="0" step="0.001" class={inputCls} bind:value={f.volume_m3} /></label>
					{/if}

					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Fecha embarque</span><input type="date" class={inputCls} bind:value={f.on_date} /></label>
					<label class="flex items-center gap-2 pt-6 text-sm"><input type="checkbox" class="h-4 w-4 rounded border" bind:checked={f.dangerous} /><span>Mercancía peligrosa (DGR)</span></label>
				</div>
				<div class="mt-4 flex justify-end"><Button onclick={calc} disabled={working}>{working ? 'Calculando…' : 'Calcular costo'}</Button></div>
			</Card.Content>
		</Card.Root>

		{#if calculated}
			<Card.Root>
				<Card.Header><Card.Title class="text-base">Opciones ({options.length})</Card.Title>
					<Card.Description>Ordenadas por costo total. El precio de venta se define en la cotización (costo + margen).</Card.Description>
				</Card.Header>
				<Card.Content>
					{#if options.length === 0}
						<p class="text-sm text-muted-foreground">No hay tarifas vigentes para esa ruta/modo. Verifica que exista un tarifario <b>activo</b> con esa ruta.</p>
					{:else}
						<div class="overflow-x-auto">
							<Table.Root>
								<Table.Header><Table.Row><Table.Head>Tarifario</Table.Head><Table.Head>Base</Table.Head><Table.Head>Cargos</Table.Head><Table.Head>Total</Table.Head><Table.Head>Detalle</Table.Head><Table.Head>Tránsito</Table.Head></Table.Row></Table.Header>
								<Table.Body>
									{#each options as o, i (o.rate_sheet_id + '-' + i)}
										<Table.Row class={i === 0 ? 'bg-emerald-50/60 dark:bg-emerald-950/20' : ''}>
											<Table.Cell class="font-medium">{o.rate_sheet_name}</Table.Cell>
											<Table.Cell>{money(o.base_cost, o.currency)}</Table.Cell>
											<Table.Cell class="text-xs">{o.charges.length ? o.charges.map((c) => `${c.concept}: ${money(c.amount, o.currency)}`).join(', ') : '—'}</Table.Cell>
											<Table.Cell class="font-semibold">{money(o.total_cost, o.currency)}</Table.Cell>
											<Table.Cell class="text-xs text-muted-foreground">{o.detail ?? '—'}</Table.Cell>
											<Table.Cell>{o.transit_days ?? '—'}</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					{/if}
				</Card.Content>
			</Card.Root>
		{/if}
	{/if}
</div>
