<script lang="ts">
	import { onMount } from 'svelte';
	import { FileSpreadsheet, Plus, Trash2, Search, Pencil, Upload, Download } 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 RateSheet, type RateMode, type ImportPreview } from '$lib/api/crm/rates';
	import { suppliersAPI, type Supplier } from '$lib/api/crm';
	import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
	import { formatDate } 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 sheets = $state<RateSheet[]>([]);
	let suppliers = $state<Supplier[]>([]);
	let loading = $state(false);
	let modeFilter = $state('');

	// modal import
	let showImport = $state(false);
	let imp = $state({ mode: 'aereo' as RateMode, name: '', supplier_id: null as number | null, currency: 'USD', valid_from: '', valid_to: '', default_origin: '' });
	let impFile = $state<File | null>(null);
	let preview = $state<ImportPreview | null>(null);
	let working = $state(false);

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

	$effect(() => { const cid = companyId; if (cid) void load(cid); });

	async function load(cid: number) {
		loading = true;
		try {
			sheets = await rateSheetsAPI.list(cid, { mode: modeFilter || undefined });
			if (suppliers.length === 0) suppliers = await suppliersAPI.list(cid).catch(() => []);
		} catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los tarifarios'); }
		finally { loading = false; }
	}

	const modeLabel = (m: string) => crmCatalogs.label('modo_tarifario', m);

	function openImport() {
		imp = { mode: 'aereo', name: '', supplier_id: null, currency: 'USD', valid_from: '', valid_to: '', default_origin: '' };
		impFile = null; preview = null; showImport = true;
	}
	async function dlTemplate() {
		if (!companyId) return;
		try { await rateSheetsAPI.downloadTemplate(imp.mode, companyId); }
		catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo descargar la plantilla'); }
	}
	function onFile(e: Event) { impFile = (e.target as HTMLInputElement).files?.[0] ?? null; preview = null; }
	async function doPreview() {
		if (!companyId || !impFile) { toast.error('Selecciona un archivo'); return; }
		working = true;
		try { preview = await rateSheetsAPI.importPreview(imp.mode, impFile, companyId); }
		catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo leer el archivo'); }
		finally { working = false; }
	}
	async function doImport() {
		if (!companyId || !impFile) return;
		if (!imp.name.trim()) { toast.error('Ponle nombre al tarifario'); return; }
		working = true;
		try {
			await rateSheetsAPI.importSheet(companyId, {
				mode: imp.mode, name: imp.name.trim(), supplier_id: imp.supplier_id,
				currency: imp.currency, valid_from: imp.valid_from || null, valid_to: imp.valid_to || null,
				default_origin: imp.default_origin || null
			}, impFile);
			toast.success('Tarifario importado');
			showImport = false;
			await load(companyId);
		} catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo importar'); }
		finally { working = false; }
	}
	async function remove(s: RateSheet) {
		if (!companyId || !confirm(`¿Eliminar el tarifario "${s.name}"?`)) return;
		try { await rateSheetsAPI.remove(s.id, companyId); toast.success('Eliminado'); await load(companyId); }
		catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo eliminar'); }
	}
	const statusCls = (st: string) => st === 'activo' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400'
		: st === 'vencido' || st === 'reemplazado' ? 'bg-muted text-muted-foreground' : 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400';
</script>

<div class="space-y-6">
	<div class="flex flex-wrap items-center justify-between gap-3">
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FileSpreadsheet class="h-6 w-6" /> Tarifarios</h1>
			<p class="mt-1 text-sm text-muted-foreground">Costos de proveedores por ruta, base de las cotizaciones.</p>
		</div>
		<Button onclick={openImport} disabled={!companyId}><Upload class="mr-1 h-4 w-4" /> Importar tarifario</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="flex flex-wrap items-center gap-3">
				<select class={inputCls} bind:value={modeFilter} onchange={() => companyId && load(companyId)}>
					<option value="">Todos los modos</option>
					{#each crmCatalogs.options('modo_tarifario') as m (m.value)}<option value={m.value}>{m.label}</option>{/each}
				</select>
			</div>
		</Card.Header>
		<Card.Content>
			{#if loading}
				<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
			{:else if sheets.length === 0}
				<p class="py-6 text-center text-sm text-muted-foreground">Sin tarifarios. Importa uno con el botón de arriba.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header><Table.Row><Table.Head>Nombre</Table.Head><Table.Head>Modo</Table.Head><Table.Head>Moneda</Table.Head><Table.Head>Rutas</Table.Head><Table.Head>Vigencia</Table.Head><Table.Head>Estatus</Table.Head><Table.Head class="text-right">Acciones</Table.Head></Table.Row></Table.Header>
						<Table.Body>
							{#each sheets as s (s.id)}
								<Table.Row>
									<Table.Cell class="font-medium"><a class="hover:underline" href={`/dashboard/crm/tarifarios/${s.id}`}>{s.name}</a></Table.Cell>
									<Table.Cell>{modeLabel(s.mode)}</Table.Cell>
									<Table.Cell>{s.currency ?? '—'}</Table.Cell>
									<Table.Cell>{s.lane_count ?? 0}</Table.Cell>
									<Table.Cell class="text-xs">{s.valid_from ? formatDate(s.valid_from) : '—'} → {s.valid_to ? formatDate(s.valid_to) : '—'}</Table.Cell>
									<Table.Cell><span class="inline-flex rounded-full px-2 py-0.5 text-xs {statusCls(s.status)}">{s.status}</span></Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/crm/tarifarios/${s.id}`}><Pencil class="mr-1 h-4 w-4" /> Abrir</Button>
										<Button variant="ghost" size="sm" onclick={() => remove(s)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						</Table.Body>
					</Table.Root>
				</div>
			{/if}
		</Card.Content>
	</Card.Root>
</div>

{#if showImport}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" role="presentation" onclick={() => (showImport = false)}>
		<div class="max-h-[92vh] w-full max-w-2xl overflow-y-auto rounded-lg border bg-card p-6 shadow-lg" role="dialog" aria-modal="true" tabindex="-1" onclick={(e) => e.stopPropagation()}>
			<h3 class="mb-4 flex items-center gap-2 text-base font-semibold"><Upload class="h-4 w-4" /> Importar tarifario</h3>
			<div class="grid gap-3 sm:grid-cols-2">
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Modo *</span>
					<select class={inputCls} bind:value={imp.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">Nombre *</span><input class={inputCls} bind:value={imp.name} placeholder="Tarifario NLU 2º sem 2026" /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Proveedor</span>
					<select class={inputCls} bind:value={imp.supplier_id}><option value={null}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.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={imp.currency}><option value="USD">USD</option><option value="MXN">MXN</option><option value="EUR">EUR</option></select>
				</label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Vigencia desde</span><input type="date" class={inputCls} bind:value={imp.valid_from} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Vigencia hasta</span><input type="date" class={inputCls} bind:value={imp.valid_to} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Origen por defecto</span><input class={inputCls} bind:value={imp.default_origin} placeholder="NLU" /></label>
			</div>

			<div class="mt-4 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-3">
				<Button variant="outline" size="sm" onclick={dlTemplate}><Download class="mr-1 h-4 w-4" /> Descargar plantilla</Button>
				<input type="file" accept=".xlsx" class="{inputCls} flex-1" onchange={onFile} />
				<Button variant="outline" size="sm" onclick={doPreview} disabled={working || !impFile}>Vista previa</Button>
			</div>

			{#if preview}
				<div class="mt-3 rounded-md border p-3 text-sm">
					<p class="mb-2">Filas válidas: <b>{preview.valid}</b> / {preview.total}. Columnas: <span class="font-mono text-xs">{preview.columns.join(', ')}</span></p>
					{#if preview.rows.some((r) => r.errors.length)}
						<div class="max-h-32 overflow-y-auto text-xs text-destructive">
							{#each preview.rows.filter((r) => r.errors.length).slice(0, 20) as r (r.row)}<div>Fila {r.row}: {r.errors.join('; ')}</div>{/each}
						</div>
					{/if}
				</div>
			{/if}

			<div class="mt-5 flex justify-end gap-2 border-t pt-4">
				<Button variant="outline" onclick={() => (showImport = false)}>Cancelar</Button>
				<Button onclick={doImport} disabled={working || !impFile || preview?.valid === 0}>{working ? 'Importando…' : 'Importar'}</Button>
			</div>
		</div>
	</div>
{/if}
